tags:

views:

5136

answers:

6

How do I programatically force an onchange event on an input?

I've tried something like this:

var code = ele.getAttribute('onchange');
eval(code);

But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.

A: 

if you're using jQuery you would have:

$('#elementId').change(function() { alert('Do Stuff'); });

or MS AJAX:

$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });

Or in the raw HTML of the element:

<input type="text" onchange="alert('Do Stuff');" id="myElement" />

After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:

$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}

Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.

Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:

$get('elementId')._events

It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.

Slace
I believe he wants to fire the actual event, not run a function when the event is fired... i _think_. lol
Kolten
+6  A: 

ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:

document.getElementById("test").onchange()

Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly

Kolten
eval for objectifying JSON ;)
Slace
Agreed about eval - I pulled that code from http://stackoverflow.com/questions/33860/is-it-possible-to-call-javascripts-onsubmit-event-programatically-on-a-form as an example of something I don't want.
Soldarnal
A: 

Taken from the bottom of QUnit

function triggerEvent( elem, type, event ) {
    if ( $.browser.mozilla || $.browser.opera ) {
     event = document.createEvent("MouseEvents");
     event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);
     elem.dispatchEvent( event );
    } else if ( $.browser.msie ) {
     elem.fireEvent("on"+type);
    }
}

You can, of course, replace the $.browser stuff to your own browser detection methods to make it jQuery independent.

To use this function:

var event;
triggerEvent(ele, "change", event);

This will basically fire the real DOM event as if something had actually changed.

Chris MacDonald
+2  A: 

For some reason ele.onchange() is throwing a "method not found" expception for me in IE on my page, so I ended up using this function from the link Kolten provided and calling fireEvent(ele, 'change'), which worked:

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

I did however, create a test page that confirmed calling should onchange() work:

<input id="test1" name="test1" value="Hello" onchange="alert(this.value);"/>
<input type="button" onclick="document.getElementById('test1').onchange();" value="Say Hello"/>

Edit: The reason ele.onchange() didn't work was because I hadn't actually declared anything for the onchange event. But the fireEvent still works.

Soldarnal
I like this method of browser detection (by object detection) better than the example I provided.
Chris MacDonald
A: 

this fireEvent example is awesome. i have been looking for a way to have cfinput and cfselect bind listeners pickup ajax changed bound fields. after 2 days of trying to use the extended yahoo YUI js library in coldfusion, and ColdFusion.Bind.assignValue to no avail this worked flawlessly

+5  A: 

In jQuery I mostly use:

$("#element").trigger("change");
Danita
tihs helped me! I was setting the value of a checkbox (checked or not) using code and the event was not firing in IE at all no matter what i did. I tried blur() focus() and a few other things. after i set the value i called trigger and i added a click event to call trigger as well. It causes multiple fires but it doesnt matter to me. In IE I add checkboxes through code and you have to click on them twice before the change event fires. Thanks for this tip.
DustinDavis