fightstarr20
fightstarr20

Reputation: 12598

JavaScript addEventListener for 2 different inputs

I currently have an event listener that fires when input is changed like this:

input = document.getElementById("inputfield1");

input.addEventListener("change", function(e) {
    console.log("Do Something with inputfield1");
});
<input id="inputfield1">

I now also want to add a second input so that the event is fired if inputfield2 changes, too.
Can I just add it using an OR statement? Or should I create a whole new event listener for the 2nd field?

Upvotes: 0

Views: 1423

Answers (3)

Slai
Slai

Reputation: 22876

function f(element) { console.log(element.id, element.value); }
<input id="inputfield1" onchange="f(this)">
<input id="inputfield2" onchange="f(this)">

or

function f(event) { 
  var element = event.currentTarget
  console.log(element.id, element.value)
}

document.getElementById("inputfield1").addEventListener("change", f)
document.getElementById("inputfield2").addEventListener("change", f)
<input id="inputfield1">
<input id="inputfield2">

Upvotes: 1

Osama
Osama

Reputation: 3040

use querySelectAll() and for loop

  function myFunction(){
    input =document.querySelectorAll("#inputfield1 , #inputfield2");
    var i;
    for (i = 0; i <input.length; i++) {
    input[i].addEventListener("keypress", function() {
        alert("hi from"+this.id);
    });
    }
    }
    myFunction();
 <input id="inputfield1">
    <input id="inputfield2">

Upvotes: 0

Christos
Christos

Reputation: 53958

You have to attach explicitly the event handler for each element. Below there is a snippet, where it is shown how you can do this.

document.querySelectorAll('.jsInputField')
        .forEach(function(element){
                element.addEventListener('change', function(event){
                    var elementId = event.currentTarget.getAttribute('id')
                    console.log("Do Something with " + elementId);
                });
       });
<input id="inputfield1" class="jsInputField">
<input id="inputfield2" class="jsInputField">

Update

As Ram has pointed out in his comment, NodeList.prototype.forEach, is a method of NodeList that is supported from latest browsers (e.g. Chrome 51 etc.). For further info, please have a look here.

In order you avoid to use the polyfill that is presented at the link above for cases that this method is not supported, you could make use of a simple for statement.

Upvotes: 0

Related Questions