-3

I'm trying to do the following:

function() {
 var elements = document.getElementsByClassName('class');
 var length = elements.length;
 for (var i = 0; i < length; i++) {
  var element = elements[i];
  element.addEventListener('input', function() { return handleInputEvent(element); }, false);
 }
}
function handleInputEvent(element) {
 var value = element.value; // empty string
}

but when I try to get the element's value, it keeps coming back as an empty string even though I'm typing in a number or letter. Any ideas?

html is a bunch of inputs

<input type='text' class='class'/>
<input type='text' class='class'/>
<input type='text' class='class'/>
duxfox--
  • 9,097
  • 15
  • 55
  • 116

1 Answers1

2

You're redefining element every time you go through the loop. When you use element in each event function, it means that the function will be executed using the value of element at the time of function execution, so element will always refer to the last value element, which would be the last element in elements. So if the last element in elements has a value of '', then the output will be ''.

But not only that, you don't actually return the element.value, you simply leave it as a local variable inside the handling function. You should replace

var value = element.value;

With

return element.value;

Or

console.log(element.value);
Oliver
  • 1,530
  • 1
  • 16
  • 29
  • nailed it, good catch. I just tested and that seems to be happening. – duxfox-- Oct 09 '15 at 21:58
  • But `element` is passed as an argument in `handleInputElements()`; it's not the global variable. It has local scope - it will not be affected by the `elements[]` array. This is wrong. – Jonathan Lam Oct 09 '15 at 21:58
  • I don't need to return a value, I do other stuff in the function, but that's outside the scope of the question – duxfox-- Oct 09 '15 at 22:02
  • @jlam55555 I know I only covered part of the problem, I edited after reading your comment. – Oliver Oct 09 '15 at 22:02
  • @AbdulAhmad The not returning anything is causing the empty string -- the empty string is because there *is no value* returned! It **totally** is in the scope of your question. – Jonathan Lam Oct 09 '15 at 22:02
  • and @Tobsta that edit covers it now – Jonathan Lam Oct 09 '15 at 22:04
  • @jlam55555 what are you talking about. I don't need to return a value because I use it in other operations inside the function and then update an html element with the result. – duxfox-- Oct 09 '15 at 22:06
  • @AbdulAhmad You didn't show that in your code though. – Jonathan Lam Oct 09 '15 at 22:07
  • @jlam55555 I told you its outside the scope of the question. now please stop bugging me – duxfox-- Oct 09 '15 at 22:07
  • 1
    @AbdulAhmad Ah ok, that was just unclear. It looked as if that was one of the problems. – Oliver Oct 09 '15 at 22:07