justin
justin

Reputation: 1709

jQuery checking and unchecking checkboxes

I have to check and uncheck the checkboxes. But it is not working well.

Example: When the status is active on the 1st load:

Example: WHen the status is inactive on the 1st load:

Here is my sample code:

var statusCheck = $('.status-box');

$.ajax({
    url: 'sample/url',
    type: 'POST',
    data: {
        user_id: ids,
        status: statusVal
    },
    success: function (response) {
        if (response == 'ok') {
            $.each(statusCheck, function () {
                var _this = $(this);

                if (_this.is(':checked')) {
                    _this.removeAttr('checked');
                } else {
                    _this.attr('checked', '');
                }
            });
        }
    }
});

Upvotes: 0

Views: 255

Answers (2)

Anton Belev
Anton Belev

Reputation: 13543

I had problems (strange anomalies) with checking and unchecking checkboxes with JQuery. I was using .attr and .removeAttr and when I changed it to .prop('checked',false/true) I resolved the problem.

Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes. Reference:

Note you should be using JQuery 1.6 +.

Upvotes: 2

Kamran Ahmed
Kamran Ahmed

Reputation: 12438

var statusCheck = $('.status-box')

$.ajax({
        url     : 'sample/url',
        type    : 'POST',
        data    : { user_id: ids, status: statusVal },
        success : function( response ) {
            if( response == 'ok' ) {
                $.each(statusCheck, function(){
                    var _this    = $(this);

                    if( _this.is(':checked') ) {
                        _this.removeAttr('checked');
                    } else {
                        _this.attr('checked', 'checked');
                             // ...............^ here ^
                    }
                });
            }
        }
    });

Try this: _this.attr('checked', 'checked');

Also .prop() from this Link might do the magic ;)

Upvotes: 2

Related Questions