-2

I got a problem when trying to make onchange listener for input in JavaScript:

var apple = document.getElementById("apple");
apple.addEventListener("change", validate("apple"));

function validate(fruitName){
    var qty = parseInt(document.getElementById(fruitName).value);
    console.log(qty);
}

I am trying to check everytime when the user input something for 'apple' input, I will print the quantity at console. But by doing this, It only ran the first time when I refreshed the browser by printing out a NaN and does not work even when I changed the input for 'apple'.

Any ideas?

Thanks in advance.

QWERTY
  • 2,303
  • 9
  • 44
  • 85

1 Answers1

7

You have to reference the function, not call it, and you don't need to pass in the name to use as an ID to get the elements, the element is already available in this

var apple = document.getElementById("apple");

apple.addEventListener("change", validate);

function validate(event){
    var qty = parseInt(this.value, 10);
    console.log(qty);
}

Whenever you add parentheses you call the function, and whatever is returned is passed to the event handler.
As functions return undefined by default, that's what you get.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Sorry but what I am trying to do is I try to pass the string which is the fruitName to the validate() as well – QWERTY Oct 12 '16 at 15:45
  • 1
    As that's also the ID, you get that name with `this.id`, but it makes no sense to do `document.getElementById(this.id)`, as it will just return the same thing as `this`. – adeneo Oct 12 '16 at 15:46
  • Sorry but what I am trying to do is I actually got a few of fruits. Then, when I call the validate, I wanted to pass in the fruit name as well as it will be used somewhere else in the code. The var apple is actually the quantity, sorry for the naming convention – QWERTY Oct 12 '16 at 15:50
  • I'm a little confused, you have an input, and you change that input, and you get the quantity with `this.value`, why would you pass in the quantity? Have you tried the above code ? – adeneo Oct 12 '16 at 15:57
  • https://jsfiddle.net/adeneo/cb8xox7q/ – adeneo Oct 12 '16 at 15:59
  • Nevermind, I got it working already. Thanks! – QWERTY Oct 12 '16 at 16:01