Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically changing checkbox does not fire change event

I have the following code here:

$('input[type="checkbox"][id="gridlines"]').change(function () {
    alert('hello world');
});

$('#gridlines').prop('checked', true);

When I load my page, the checkbox is checked, but the "hello world" does not get prompted.

However, when I click on the checkbox manually, "hello world" gets prompted.

What gives?

like image 829
Null Reference Avatar asked Apr 23 '14 06:04

Null Reference


Video Answer


2 Answers

You need to call change() or use trigger() to tirgger the change event when values is changed through code.

Using .change()

$('#gridlines').prop('checked', true).change();

Using .trigger()

$('#gridlines').prop('checked', true).trigger("change");
like image 121
Adil Avatar answered Oct 12 '22 16:10

Adil


That is how it is suppose to work, only user interaction is support to trigger the change event

You can trigger it manually using .change()/.trigger('change');

$('#gridlines').prop('checked', true).change();

change

The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.

like image 5
Arun P Johny Avatar answered Oct 12 '22 17:10

Arun P Johny