chapmanio
chapmanio

Reputation: 2991

Trigger standard "change" event on form object - to be picked up by any listeners on it

I have a noConflict instance of jQuery that gets automatically included on some of my pages. This code will automatically update any matching form fields it finds. Eg:

var jq = $.noConflict(true);

if (jq('input[name="field_name"]').length > 0) 
{
    jq('input[name="field_name"]').val('field_value');
}

I want this code to then trigger that standard in-built "change" event on that form object, so that any listeners/event handlers attached to it will be fired. Is this possible?

I know you can trigger change events in jquery, but these will only be picked up by the event handlers in the same instance. Eg:

jq('input[name="field_name"]').trigger('change');

I want to be able to trigger the change event for anything that may be listening for it, be it another instance of jQuery, or standard javascript.

Can anyone help or am I reaching too far?

Thanks

Upvotes: 1

Views: 4918

Answers (1)

Gordon Tucker
Gordon Tucker

Reputation: 6773

You can trigger events manually. jQuery actually triggers native events as well, but it appears that jquery doesn't trigger other handlers that were registered with addEventListener though as the fiddler example shows. (see https://stackoverflow.com/a/3631714/174469 for info about native events)

Here is a fiddler that shows an example: http://jsfiddle.net/EXw4P/2/

HTML:

<input type="text" id="foobar" />

Javascript:

// Register a non-jquery handler on the textbox
foobar.onchange = function () {
    alert("explicit native onchange");   
}
foobar.addEventListener('change', function() { alert('event listener onchange') }, false);

$("#foobar").change(function () {
    alert("jquery onchange"); 
});

alert("Trigger change from jquery")
$("#foobar").trigger("change");

alert("Trigger native change event")
var fakedEvent = document.createEvent('MouseEvents');
fakedEvent.initMouseEvent('change', true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
foobar.dispatchEvent(fakedEvent);

Upvotes: 2

Related Questions