最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Programmatically changing checkbox does not fire change event - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited Sep 14, 2022 at 8:28 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Apr 23, 2014 at 6:10 Null ReferenceNull Reference 11.3k41 gold badges111 silver badges186 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 16

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

Using .change()

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

Using .trigger()

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

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.

发布评论

评论列表(0)

  1. 暂无评论