John Hoffman John Hoffman - 30 days ago 11
jQuery Question

Why does dynamically changing a checkbox not trigger a form change event?

I wrote this snippet of javascript/jQuery to change a check box.
http://jsfiddle.net/johnhoffman/crF93/

Javascript

$(function() {
$("a").click(function() {
if ($("input[type='checkbox']").attr('checked') == "checked")
$("input[type='checkbox']").removeAttr('checked');
else
$("input[type='checkbox']").attr('checked', 'checked');
return false;
});

$("input[type='checkbox']").change(function(){
console.log("Checkbox changed.");
});
});​


HTML

<input type="checkbox" />
<a href="#">Change CheckBox</a>​


Interestingly, clicking the link alters the text box, but does not trigger the form change event that calls the function that logs a message in Chrome Web Developer Console. Why? How do I make it do that?

Answer Source

Hiya demo sample http://jsfiddle.net/nPkPw/3/ && here using chaining : http://jsfiddle.net/nPkPw/5/ i.e. $("input[type='checkbox']").trigger('change').attr('checked', 'checked');

And rest @Sinetheta has another working version for you! :)

So you need to trigger the change event .trigger('change') so that event knows that change took place. Let me know if I am missing anything.

http://api.jquery.com/change/

Quote

Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

This method is a shortcut for .bind('change', handler) in the first two variations, and .trigger('change') in the third. The center code herehange event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

Thanks :) !