user1773603
user1773603

Reputation:

javascript - addEventListener with an array of input

I need to use addEventListener for automatically updating the values typed into different input text (actually 4 input tags)

Here's the HTML code :

<td class="col-md-4">
        <label for="lab1"><b>$\mathbf{M_{1}}$</b></label>                                
        <input type="text" class="form-control input-sm" id="lab1" />                    
      </td>
        <td class="col-md-4">                                                            
        <label for="lab2"><b>$\mathbf{M_{2}}$</b></label>
        <input type="text" class="form-control input-sm" id="lab2"  />                   
      </td>
    <td class="col-md-4">                                                                
        <label for="lab3"><b>$\mathbf{M_{3}}$</b></label>                                
        <input type="text" class="form-control input-sm" id="lab3" />                    
      </td>
      </tr>
   <tr>                                                                                  
       <td class="col-md-4">                                                             
        <label for="lab4"><b>$\mathbf{\Theta_{1}}$</b></label>                           
        <input type="text" class="form-control input-sm" id="lab4" />                    
      </td>

I would like to update values when they are modified, without having to click outside the input.

I tried to use the following addModifyEvent function in main :

    function addModifyEvent() {                                                              

     var inputList = document.querySelectorAll('input.form-control');   

    for (var i=0; i<inputList.length; i++)                                                   
     {  
    inputList[i].addEventListener('input', function()                                        
        {   
console.log(inputList[i].value);  });
    }       
    }     

but it doesn't work ( I get TypeError: inputList[i] is undefined).

I don't know if I shoud better do :

inputList[i].addEventListener('inputList['+i+']', 

or something closed instead of

inputList[i].addEventListener('input', 

I want to add an eventlistener for each input tag.

Anyone could tell me the right syntax ?

Thanks

Upvotes: 3

Views: 3382

Answers (6)

Ravi Teja
Ravi Teja

Reputation: 659

var inputElem = document.getElementsByTagName('input');

for(var i = 0; i < inputElem.length; i++) {
inputElem[i].addEventListener('click', function(){
    alert(this.value);
}, false);
}

Upvotes: 0

Keval Bhatt
Keval Bhatt

Reputation: 6322

As you can see in example i printed 2 console one for your input and one for your i

So your problem is:

when in listener function you are trying to access console.log(inputList[i].value); so at that time your i is 4 and your input array length is 0-3 and because of for loop i will be incremented to 4 so you got undefined because inputList[4] is not present in your array.

Working example:http://jsfiddle.net/kevalbhatt18/gqce9htx/

var input = document.querySelectorAll('input');
  console.log(input)
   for(var i=0;i<input.length;i++){
      input[i].addEventListener('input', function()
      {  
         console.log(input)
         console.log(i)
         console.log('input changed to: ', this.value);
      });

 }

debugg your error example:http://jsfiddle.net/kevalbhatt18/gqce9htx/2/

Upvotes: 1

jsNovice
jsNovice

Reputation: 646

You can use closures (if not familiar, please search it and read a bit). The code goes as below:

for (var i=0; i<inputList.length;i++)                                                   
{
     (function(i){
            inputList[i].addEventListener('input',function(){   
                  console.log(inputList[i].value);  });
         }
    })(i);
}  

Basically the value of i remains intact within the function. This is required whenever you do something in a loop that is Async.
The benefit being that you do not need to change the way you access values, except that you need to enclose them within a closure function.
Hope this solves you issue without any changes in the way to want to access the array.

Upvotes: 0

Shaunak D
Shaunak D

Reputation: 20626

At the time the event fires,

console.log(inputList[i].value);

inputList[i] will not be valid as it was part of the for loop used to bind event listeners.

Use this to get the current element on which the event was fired,

console.log(this.value);

Full code

function addModifyEvent() {
    var inputList = document.querySelectorAll('input.form-control');
    for (var i = 0; i < inputList.length; i++) {
        inputList[i].addEventListener('input', function () {
            console.log(this.value);
        });
    }
}

Upvotes: 0

jfriend00
jfriend00

Reputation: 707308

A slightly modified version of your code that uses this.value works just fine:

function addModifyEvent() {
    var inputList = document.querySelectorAll('input.form-control');
    for (var i = 0; i < inputList.length; i++) {
        inputList[i].addEventListener('input', function () {
            console.log(this.value);
        });
    }
}

Demo: http://jsfiddle.net/jfriend00/9ny3wcxu/


You can't refer to inputList[i] inside the event handler because by the time the event handler is called (sometime later) the for loop has already finished running so i points past the end of the inputList HTMLCollection object.

You can solve the problem by just using this as a pointer to the object that caused the event and thus this.value is the value of the input field that has just been modified.

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

The context of the event handler is the input element the event is fired on. Replace the inputList[i] with this:

console.log(this.value);

Upvotes: 0

Related Questions