I am trying to figure out a way to attach an event listener.
I have the following variable:
var inputs = data.context.find(':input').not(':button');
And, later in the code, I have a FOR loop, in which I use this to add a css class to some fields:
inputs[i].className += " invalidEntry";
That works fine.
What I want to do though is also attach an event handler to those same fields so that when the values in the fields are changed that css class name is removed.
So, how can I attach an event listener to inputs[i] during the FOR loop?
Add it like this:
function change(){
// this refers to the element that had the keypress event fired on it.
this.className=this.className.replace(" invalidEntry","");
}
for(var i=0;i<inputs.length;i++){
inputs[i].className += " invalidEntry";
inputs[i].addEventListener('keypress',change);
}
The change
function only needs to be defined once, and used again and again becuase the this
keyword will refer to the element was keypress
ed, so it will always be one of the input
s.