jQuery and checkbox click events
When triggering a checkbox click event via jQuery's .trigger() function, the element's reported check statement will be reversed. The check status doesn't appear to change until *after* the event has completed. When triggering the event in the normal way, by clicking on the checkbox itself, the element's checked status changes immediately. To work around this, I pass an extra parameter, called nonUI, from the jQuery .trigger() to the checkbox's click handler. If that parameter is present and set to true, the reported check status is inverted and is now what we would expect it to be. The button on the page triggers the checkbox's click event via .jQuery.trigger().
by BrownieBoy
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<title>index</title>
<meta name="description" content="" />
<meta name="author" content="Michael Brown" />
<meta name="viewport" content="initial-scale=1.0" />
</head>
<body>
<div>
<header>
<h1>Programmatic Change Event on a Checkbox</h1>
</header>
<div>
<br />
<input type="checkbox" id="myCheckbox"> <label for="myCheckbox">Here's my checkbox!</label>
</div>
<br />
<button id="butTriggerChange">Trigger checkbox click event</button>
</div>
</body>
</html>
CSS
body {
margin :20px
}
JavaScript
$("#myCheckbox").click(function(e, parameters) {
var nonUI = false;
try {
nonUI = parameters.nonUI;
} catch (e) {}
var checked = nonUI ? !this.checked : this.checked;
alert('Checked = ' + checked);
});
$("#butTriggerChange").click(function() {
$("#myCheckbox").trigger('click', {
nonUI : true
})
});