jQuery click checkbox doesn't check in firefox

2020-03-30 02:54发布

Specifically, an in memory dom of input type checkbox does not receive the 'checked' attribute (or any other checked indicator) in FireFox.

The commented line can be uncommented to see the test pass, but currently you will see the test fail in firefox.

http://jsfiddle.net/mE3xb/2/

var cb = $('<input type="checkbox" />')
//var cb = $('input'); 
if (cb.is(':checked')) alert("checkbox says it's already checked"); 
cb.click(); 
if (cb.is(':checked')) alert("checkbox clicked correctly!"); 
else alert("fail!"); 

Am I doing non-standard things? Any advice? I'm essentially relying on the jQuery .click to actually check my checkbox in the UI (and I don't want to use .attr, .prop, .val because it will break my nice encapsulation that I got going on.)

3条回答
▲ chillily
2楼-- · 2020-03-30 03:29

Use cb.prop('checked', true) instead of cb.click() to check your checkboxes

Fiddle updated http://jsfiddle.net/mE3xb/7/

查看更多
在下西门庆
3楼-- · 2020-03-30 03:32

I know this is an old question, but I just stumbled on an answer that worked for me for my unit test:

First, I toggle the checked property:

checkbox4[0].checked = !checkbox4[0].checked;

Then after that, I trigger "just" the click handler (by using triggerHandler it doesn't actually check/uncheck the box again on other browsers)

checkbox4.triggerHandler( "click" );

This simulates an user "clicking" the checkbox, and checking/unchecking it. Not as encapsulated as you might like it to be for your needs (from reading the above comments and answers) but it seems to get a slightly more thorough job done of it than the currently accepted answer.

查看更多
4楼-- · 2020-03-30 03:45

Since you are using jQuery 1.4.3, it looks like your best bet will be:

cb[0].setAttribute('checked', 'checked'); // plain old vanilla JS

jsFiddle Demo - tested in FireFox & Chrome & IE8

.click() doesn't work in many strange situations in Firefox (it is something inherently wrong/different in that browser). I would assume because it isn't actually available on the DOM yet, so it doesn't know where this event would be. This is one of the many reasons things like .prop() exist, etc.

查看更多
登录 后发表回答