JavaScript onChange event handling

When you're developing web applications you'll often encounter a situation where you react on changes of a control's data due to some user interaction. How complicated :) , well a situation where some user types something inside a text-field. If possible you'd like to react and process the change already on the client-side before having to send the page back to the server. This may increase the usability and user-friendliness of your app.
So to become more concrete, in JavaScript you register an onChange event handler on your textfield (for example. You could also react on click events on buttons etc...). So you have your text-field where you register your event handling function:
<input id="textBox1" type="text" onChange="onChangeEventHandler(event);"/>
The according function's signature would look like this:
/*
* onChange event handler
*/
function onChangeEventHandler(event){

}
Pay attention on the naming of the parameters on the calling side and on the function declaration. I've experienced sometimes problems, that the passed parameter "event" was null, just because in the registering of the handler on the text-field I've written something like onChangeEventHandler(myEvent). Now it may also be interesting to know who fired the change, since you may use this "onChangeEventHandler(..)" function on more controls on your UI (given that they follow the same logic on changes). Actually you can retrieve the sender-control from the passed event parameter. The problem? Cross-browser compatibility. If your function for instance like the following
/*
* onChange event handler
*/
function onChangeEventHandler(event){
if(event != null){
printMessage(event.target.id + ' has fired the event!');
}
}
it will work on Firefox and Safari (for Windows) but it won't on IE (I've tested only IE7). IE seems to have a different event handling model, so to make your script compatible you have to something like this:
/*
* onChange event handler
*/
function onChangeEventHandler(event){
if(event != null){
//check for browser compatibility
if(event.target){
//firefox, safari
printMessage(event.target.id + ' has fired the event!');
}else{
//IE
printMessage(event.srcElement.id + ' has fired the event!');
}
}

}

The following page demonstrates it: *click*
Kindle

Comments

0

Your ad here?