-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'/>
Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127

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,576
  • 1
  • 17
  • 31