views:

474

answers:

1

I need to detect the id of the element that generated an onchange event.

This code work in most modern browsers:

<input type="text" onchange="return onchange_handler(event);"

function onchange_handler(event) {
    var id = event.target ? event.target.id : event.srcElement.id;
    ...
    return false;
}

But it does not work in IE Mobile.

I have tried the following code, and at least the event is fired and the handler function is called, but window.event is not available when event handler is called:

<input type="text" onchange="return onchange_handler();"

function onchange_handler() {
    var event = window.event; // <= evaluated as UNDEFINED
    var id = event.target ? event.target.id : event.srcElement.id;
    ...
    return false;
}

Is there any way to obtain a reference to the fired event? Or an alternative approach to know the id of the element that caused the event.

+1  A: 

A workaround would be to pass the element to the callback: (untested)

<input type="text" id="mytextbox" onchange="return onchange_handler(this);"

function onchange_handler(element) {
    var id = element.id;
    ...
    return false;
}
Matthew Lock
Thank you, it works but it forces me to keep two versions of the scripts. I accept your answer as it is probably the only solution.
Guido