Simon Simon - 2 years ago 217
Javascript Question

Using jQuery to trigger html onclick event

<input type="text" id="test_value" name="test_value" value="xyz" />
<input id="test_default" name="test_default" type="checkbox" onclick="with(this.form.elements['test_value']) { disabled = this.checked; if (this.checked) { value = ''; } else {if(value=='') {value=' '; value = '';}}};" />

The inline onclick is generated by a cms which I have no control of.
I want to execute
with jQuery but that doesn't work because it's not bound to the jQuery event manager.

I've been trying variations of

$("#test_default").click(function (e) {
$("onclick").apply(checkbox, [e]);
return false;

but with no avail. Please Help.


There are dozens of different functions that may be in inline in the onclick. It isn't really an option to duplicate them and run them in parallel.

The answers work in a small demo but not in the live environment. Please look at I need the checkbox to be triggered programatically.

Bizarrely only
triggers the event correctly. Can anyone explain this?

Answer Source

Call the native DOM's onclick directly (see demo):


Or, without jQuery at all,



The actual problem is with the interaction between jQuery's .click() and the inline onclick code. jQuery's .click() actually does two things: it first triggers any event handlers, including the inline onclick code, then it causes the checkbox to become checked.

The problem arises because the inline code tests whether the checkbox is checked. Because this is triggered first, the code finds that the checkbox isn't checked, and doesn't do anything. Now after this is finished, jQuery then goes and checks the checkbox.

How do we fix this? We check the checkbox manually first, then call the inline handler. Unfortunately, we can't use jQuery's .click() to call the inline handler, because it will uncheck the checkbox again (it will also call other jQuery-bound event handlers if you add these in the future, you probably don't want that). Therefore we use the native DOM method I described earlier, since its only effect is to run the inline code.

Final code is this:

$("#metadata_field_text_10190_default").attr("checked", true)[0].onclick();

See demo: (I included a console.log in the inline code for the demo to prove that the inline code was running. Remove this if your browser is not Firefox or Chrome or it will crash).

Update again:

I didn't see your solution earlier Simon, thanks for reminding me about [0].click(). Essentially it is the native equivalent for jQuery's .click() and works because it does what I described above (checking the checkbox first, and then calling the inline code). A warning though: this will also call any event handlers bound with jQuery, which may not be what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download