Hirashi Hirashi - 4 months ago 6
jQuery Question

Using keyup on input with attribute name

Im doing application and I have a problem with "addEventListener" and "keyup".
So, i have this html code:

<input class="width50" type="number" name="metraz" value="<?php echo $metraz; ?>" />

And JS code:


If i write in html "onkeyup="validate_numb('nameoffield')" - will be fine, but if i trying code I pasted before - then isn't working. Anybody have sugestions where i have an error?

That is all the code (something isn't working here because function validate_numb calls me document.getElementsByName(name)[0].value - undefined after i used for loop and array)

var items = [
for(i=0; i<items.length; i++){
document.getElementsByName(items[i])[0].addEventListener("keyup", function(){

function validate_numb(name){//argumentem jest nazwa pola
var input = document.getElementsByName(name)[0].value;
var parsed_input = parseInt(input);//wartosc pola zamieniana na liczbe całkowitą
if(isNaN(parsed_input) || parsed_input<0 || input!=parsed_input){
return false;
return true;


The second argument to addEventListener needs to be a function.

You are calling validate_numb immediately and passing its return value (which, presumably, is not a function).

The quick and dirty solution to this would be:

...addEventListener("keyup",function () { validate_numb("metraz") });

The better solution would be to rewrite the function so that the name wasn't needed at all.

function validate_numb(event) {
    var element_to_test = this;
    // etc etc

...addEventListener("keyup", validate_numb);