简体   繁体   中英

Javascript can't apply an existing function to onkeyup

I have a bunch of HTML number inputs, and I have grabbed them by

x=document.querySelectorAll('input[type="number"]');

I then try and iterate through this with a for-loop, and apply an onkeyup function. The function is this:

t=function(elem){


elem.onkeyup=function(e) {
  if(!/[\d\.]/.test(String.fromCharCode(e.which))) {
    elem.value='';
}
};
};

Basically, what it does is clear the value of the input if there is a letter typed in. I know i can apply it via HTML

<input type='number' onkeyup='t(this)'/>

But how can I do it with javascript? I tried iterating through it with

x=document.querySelectorAll('input[type="number"]');
for(i=0; i<x.length; i++){
    x[i].onkeyup=t(this);
}  

but it doesn't work. What am I doing wrong? How can I do this? Please regular JavaScript answers only, no jQuery or other frameworks/libraries.

change

x[i].onkeyup=t(this);

to

x[i].onkeyup=t(x[i]);

because this isn't what you want it to be

Apologies, all. I found my answer. Agreeing with Jaromanda X, I needed to change

x[i].onkeyup=t(this);

to

x[i].onkeyup=t(x[i]);

This (pun intended ;)was part of the problem, but the main problem was that the valid property name is

keyup=function();

and not

onkeyup=function(){}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM