Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery is changing checkbox value but the checkbox is not displaying as checked

I have a list with a checkbox and some text (like email's inbox). I want to check/uncheck the checkbox when i click anywhere on the list item (row). I have used following code on click event of the row:

$(this).find(".cbx input").attr('checked', true); 

For first time, it show the checked checkbox. But when I click select it next time the value of checkbox checked="checked" updates in the html code (i checked through firebug) but the checkbox does not displayed as checked.

like image 732
Gaurav Avatar asked Aug 07 '13 08:08

Gaurav


2 Answers

With .attr() you set the value of an attribute in the DOM tree. Depending on the browser, browser version and jQuery version (especially 1.6), this does not always have the desired effect.

With .prop(), you manipulate the property (in this case, 'checked state'). I strongly recommend using .prop() in your case, so the following will toggle correctly:

$(this).find(".cbx input").prop('checked', true); 

For further information, please refer to the documentation of .prop().

like image 187
UweB Avatar answered Oct 04 '22 20:10

UweB


Almost right, just use 'checked' instead of true:

$(this).find(".cbx input").attr('checked', 'checked'); 

Update: Alternatively, you can use this with newer JQuery versions:

$(this).find(".cbx input").prop('checked', true); 
like image 26
Rob Avatar answered Oct 04 '22 22:10

Rob