2

I am trying to add eventlistener to input elements on an html with an inputListener function with a parameter as shown below. But this way does not work. I do not understand why I cannot pass the parameter to eventlistener function.

for (let index = 0; index<inputElements.length; index ++) {
  inputElements[index].addEventListener("input",inputListener(index));
}

function inputListener(index){
  if (inputElements[index].value.length>=5) {
      inputElements[index].style.border="none";
  }
  else{
       inputElements[index].style.border="solid 3px red";
 }
}`
  • Read this [addEventListener](https://www.w3schools.com/jsref/met_document_addeventlistener.asp) page for example. – Jeroen Heier Jul 21 '18 at 06:37
  • *"I do not understand why I cannot pass the parameter to eventlistener function."* `addEventListener` expects to be passed a function. You are passing the **return value** of `inputListener`, which is `undefined`. – Felix Kling Jul 21 '18 at 07:07

3 Answers3

2

You need to access the element reference from within the event listener using this and not by passing index in the listener function. Since you are validating the length of the text inside the input element you could use keyup event listener for that and validate for the length of the text.

var inputElements = document.querySelectorAll('input');
for (let index = 0; index<inputElements.length; index ++) {
  inputElements[index].addEventListener("keyup",inputListener);
}

function inputListener(){
  if (this.value.length>=5) {
      this.style.border="none";
  }
  else{
       this.style.border="solid 3px red";
 }
}
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • Thank you. It worked. But I do not want to use keyup since I want to catch the input value continiously even while any key pressed an held. Keyup only validates when key is up. – Nebi Sarikaya Jul 22 '18 at 03:43
  • What if I want to pass a parameter to inputlistener function other than the index parameter? – Nebi Sarikaya Jul 22 '18 at 03:46
0

Try by calling it from the callback function

function inputListener(index) {
  if (inputElements[index].value.length >= 5) {
    inputElements[index].style.border = "none";
  } else {
    inputElements[index].style.border = "solid 3px red";
  }
}

for (let index = 0; index < inputElements.length; index++) {
  inputElements[index].addEventListener("input", function(e) {
    inputListener(index)
  });
}
brk
  • 48,835
  • 10
  • 56
  • 78
0

it's enough to use the keyword "this" from within the function to refer the object (inputElements[index]), no need to pass the index.

Keerti
  • 159
  • 2
  • 6