1

I'm trying to ensure at least 1 checkbox in a group always remains checked, but I'm having difficulty.

I have multiple checkboxes whose name starts with post_type[. The function runs for the on('change') call just fine, with the problem occurring when I check to see if the input is a checkbox that is checked, where I get the following error.

value.is is not a function

Can someone please help me troubleshoot my code? Thanks.

$(document).ready(function($){

    $('input[name^="post_type["]', '#site-search').on('change', function(){

        var checks = $('input[name^="post_type["]');
        var one_checked = is_one_checked(checks);

        if(one_checked === false){
            $(this).attr('checked', 'true');
        }

    });

});

function is_one_checked(checks){

    var checked = false; // Wheteher or not at least one box is checked (false by default)

    $(checks).each(function(key, value){
        if(value.is(':checkbox') && value.is(':checked')){
            checked = true;
        }
    });

    return checked;

}
4

4 回答 4

1

Try it like this:

 $(checks).each(function(key, value){
    if($(this).is(':checkbox') && $(this).is(':checked')){
        checked = true;
    }
});
于 2013-05-15T07:38:05.770 回答
1

Use $(this), not value, in the loop

$(checks).each(function(key, value){
    if($(this).is(':checkbox') && $(this).is(':checked')){
        checked = true;
    }
});
于 2013-05-15T07:38:25.163 回答
1

The reason why value.is(':checked') doesn't work is because in the loop, value is passed as the raw DOM object. .is() is a jQuery method, so you'd have to wrap value in a jQuery object in order to use it:

$(value).is(':checked')

于 2013-05-15T07:45:23.733 回答
0

specify attr in your html checked="checked" then why not using .attr :

if($(this).attr('type') == 'checkbox' && $(this).attr('checked') == 'checked'){
        $(this).attr('checked','checked')
    }
于 2013-05-15T08:42:05.717 回答