Reputation: 851
Im using javascript and jsp for creating rows dynamically. When value in a particular cell changes, onchange event will be fired and the message will be given. When an onchange event is used in java script, first i tried to pass the id directly,
element1.onchange=checkInputValue(element1.id);
onchange event fired even when cell gets created. Later when i changed to
element1.onchange = function(evt){ testInputElement(this.id); };
and inside "testInputElement", the onchange event is called and the function worked fine. What is the use of this? Why we need to pass the function inside the function? Is there any other way? TIA
Upvotes: 0
Views: 434
Reputation: 3663
The onchange
property allows you to specify a function that should be executed whenever that element changes. In your first example you are assigning the return value of checkInputValue
to onchange
, which the element can't execute.
What you want to do is assign a function that should be executed whenver the elemnent changes, which you correctly do in the second example.
If you don't want to pass a new function to onchange
, you could instead modify checkInputValue
to accept a change event. The change event contains information about where the event originated, including the elemnt.
function handleOnChange(event) {
var id = event.target.id;
// do some stuff
}
// pass a reference to the function, rather than executing it.
// when element1 changes it will call handleOnChange, and pass an
// event object
element1.onchange = handleOnChange;
Upvotes: 1