jquery attr('checked','checked') works only once
Asked Answered
Y

2

26

I have a problem finding reason for the following jquery/checkbox behaviour.

$( this.obj + ' table.sgrid-content > thead > tr > th > input.select_all' ).on( 'click' , {grid:this} , function(event){

var grid = event.data.grid;

if( $(this).is(':checked') ){

    $( grid.obj + ' table.sgrid-content > tbody > tr > td > input.select ' ).attr('checked','checked');
    $( grid.obj + ' .sgrid-content > tbody > tr > td > input.select ' ).parents('tr').addClass('ui-state-highlight');

} else {

    $( grid.obj + ' table.sgrid-content > tbody > tr > td > input.select ' ).removeAttr('checked');
    $( grid.obj + ' table.sgrid-content > tbody > tr > td > input.select ' ).parents('tr').removeClass('ui-state-highlight');

}

});

The code is intended to work as follows: - click on input.select_all triggers the event - if input.select_all is checked: add attribute checked to all checkboxes marked as .select within table.sgrid-content - if not: remove the 'checked' attribute from all input.select items.

Yet another simple grid function. And it works. The weird part is, it works only once. By that I mean, you can select all the checkboxes and deselect them. After that operation "Select all" function stops working.

Another weird thing is, when i check dom elements with firebug they all become checked='checked' attr as they should, but they display and behave as they were not checked.

Selectors work as they should. The code part with adding/removing ui-state-highlight works all the time.

Word of explenation: grid - is the object that I pass to get grid.obj ( basically ID of a ceratain div )

Please give me your opinion.

Yttria answered 7/3, 2013 at 8:40 Comment(2)
use .prop('checked',true) and .prop('checked',false) instead of .attr('checked','checked') or .removeAttr. attr for manipulating check/selected states is now deprecated in jQueryCortezcortical
thanks, now when you mention it, the problem started after upgrading jquery lib. Thanks a lot, did't know that!Yttria
W
78

Use prop('checked', true / false) instead of removeAttr

$('input[name=foo]').prop('checked', true);
$('input[name=foo]').prop('checked', false);
Winnow answered 7/3, 2013 at 8:44 Comment(3)
use .prop instead of .attrCortezcortical
saved me a headache too :)Justiciary
this was useful for me as well. thanks. I have a query as well. What is the difference between prop and attr? aren't they both do same work?Noon
C
3

You can change the attribute, and that will also change the property, if the element is untouched. Once the element leaves this initial state, changing the attribute no longer affects the property. The exact behavior probably varies between browsers.

Instead of .attr('checked', 'cheked') use .prop('checked', true)

Complete answered 17/10, 2016 at 9:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.