javascript - Listen for keyup on all input fields -
im trying capture keyup on input fields on page.
my current code is:
var els = document.queryselectorall('input'); (var = 0; < els.length; += 1) { addevent('keyup', els[i], makehandler(els[i])); } function makehandler(field) { console.log(field.value); } function addevent(evnt, elem, func) { if (elem.addeventlistener) { elem.addeventlistener(evnt,func,false); } else if (elem.attachevent) { elem.attachevent("on"+evnt, function(e) { e = e || window.event; if (!e.preventdefault) { e.preventdefault = preventdefaultonie; } func.call(this, e); }); } else { // no elem[evnt] = func; } }
but reason capturing value on page load, not once begin type in of fields.
any ideas i'm doing wrong?
the problem makehandler
function. makehandler(els[i])
being evaluated , return value (undefined
, in case) being passed addevent
handler. try:
function makehandler(field) { return function() { console.log(field.value); }; }
this way, makehandler(els[i])
return function addevent
can attach keyup
.
alternatively, use:
function makehandler() { console.log(this.value); // 'this' field event occurred on }
and use:
addevent('keyup', els[i], makehandler);
side-note
i noticed slight error in code:
else { // no elem[evnt] = func; }
i think want set elem["on" + evnt]
instead.
Comments
Post a Comment