2

Есть n-нное количество input. Они все с одним классом. При каждой загрузке страничке их кол-во разное от 10 до 50. Нужно отследить фокус и значения inputa на котором фокус. Пример ниже не работает.

var elem = document.getElementsByClassName('myinput');
for (var i = 0; i < elem.length; i++) {
  elem[i].id = 'phonemid' + i;
};
setInterval(function() {
  for (var i = 0; i < elem.length; i++) {
    var last = document.getElementById("phonemid" + i);
    last.onfocus = function() {
      var my = elem[i];
      console.log(my.value);
    };
  };
}, 300);
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">

Отследить значение - это я кликаю на любой input ввожу туда любую цифру и с каждый изменением input-a мне приходит значение этого input-а в консоль.

1 ответ 1

2

var elem = document.getElementsByClassName('myinput');

for (let i = 0; i < elem.length; i++) {
  elem[i].addEventListener('input', function() {
    console.log(this.value, 'this index ' + i);
  })

}
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">
<input class="myinput">

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.