Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/javascript different behaviours with user click and programatically click a checkbox

A bit hard to explain, so I've set up a jsFiddle here.

Basically, I have some behaviour triggered when a user clicks a checkbox. In another place I'm trying to programatically click the check box and I need to see the exact same behaviour. It doesn't work, seemingly something to do with the order of the click and determining the checked attribute.

How can I get the behaviour I'm looking for without resorting to a hack?

like image 522
fearofawhackplanet Avatar asked Jul 01 '26 14:07

fearofawhackplanet


2 Answers

I tend to use change handler here instead (since jQuery normalizes the behavior, it doesn't require a blur), then fire that event like this:

$('span').click(function() { $('.test').click().change(); });

Then, you're explicit about the order...and you don't have the issue of the native action vs event handler order, you can test it out here.

like image 153
Nick Craver Avatar answered Jul 04 '26 03:07

Nick Craver


You don't need to put javascript for this behaviour... just use this html syntax :

<input type="checkbox" id="myid" />&nbsp;<label for="myid">My Label</label>

If you want to add javascript listners, you can add change or click to input field.

:)

OR you should do that using jquery :

$('span').click(function() { $('.test').trigger('click'); });
like image 21
Patrick Ferreira Avatar answered Jul 04 '26 05:07

Patrick Ferreira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!