简体   繁体   中英

Checking a set of checkbox if a checkbox is checked in Bootstrap or not.

Hello, I'm having a problem when performing this in bootstrap 3. I have this code working in jsfiddle but it doesn't work bootstrap.

Here's the jsfiddle

HTML

<div class="col-md-3 span6 privilege-container-b">
<label class="checkbox">
    <input type="checkbox" name="mypriv" value="test_priv1" class="test_priv1">Checkbox 1</label>
<label class="checkbox">
    <input type="checkbox" name="mypriv" value="test_priv2" class="test_priv2">Checkbox 2</label>
<label class="checkbox">
    <input type="checkbox" name="mypriv" value="test_priv3" class="test_priv3">Checkbox 3</label>
<label class="checkbox">
    <input type="checkbox" name="mypriv" value="test_priv4" class="test_priv4">Checkbox 4</label>
<label class="checkbox">
    <input type="checkbox" name="mypriv" value="test_priv5" class="test_priv5">Checkbox 5</label>
<label class="checkbox">
    <input type="checkbox" name="mypriv" value="test_priv6" class="test_priv6">Checkbox 6</label>
</div>

Jquery

$('.test_priv1').change(function () {
    var val = $('.test_priv1').is(':checked');
    if (val === true) {
        $('.test_priv2, test_priv3').prop('checked', true);
        $('.test_priv2, test_priv3').prop('disabled', true);
    } else {
        $('.test_priv2, test_priv3').prop('checked', false);
        $('.test_priv2, test_priv3').prop('disabled', false);
    }
    return false;
});

The code above doesn't work. My goal is if test_priv1 is checked, test_priv2 and test_priv3 will be checked and locked. Any thing wrong with my code? Please correct me guys. Thanks

I would add the dot to the text_priv3 selector and do

Live Demo

$(function() {
    $('.test_priv1').on("click", function () { // IE<9 triggers change after blurred
        var checked = $(this).is(':checked');
        var $otherChecks = $('.test_priv2, .test_priv3');
        $otherChecks.prop('checked', checked);
        $otherChecks.prop('disabled', checked);
        $otherChecks.parent().toggleClass("disabled",checked);
    });
});

Note I also greyed the label text

If you by the way want to grey out all the other boxes, regardless of class you can do

var $otherChecks = $("input[name='mypriv']:not('.test_priv1')");

or

var $otherChecks = $("input[name='mypriv']").not(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM