简体   繁体   中英

jQuery Select All Checkbox with toggleClass

I have seen other examples of this but have not successfully gotten this to function correctly. The examples I have seen also are just using regular checkboxes. I have used a class to stylize the checkbox with a sprite sheet so having a bit of trouble taking the ideas of these other examples and applying them to my case.

Here is the mark up:

<div id="showHideAll"">Show/Hide All<input type="checkbox" id="allCheck" name="pinSet" class="pinToggles" onclick="checkAllLinks()">
    <label for="allCheck" class="css-label"></label></div>
</div>

<div>Opt1<input type="checkbox" id="opt1Check" name="pinSet" class="pinToggles" onclick="checkOpt1Links()">
    <label for="opt1Check" class="css-label"></label>
</div>

<div>Opt2<input type="checkbox" id="opt2Check" name="pinSet" class="pinToggles" onclick="checkOpt2Links()">
     <label for="opt2Check" class="css-label"></label>
</div>

<div>Opt3<input type="checkbox" id="opt3Check" name="pinSet" class="pinToggles" onclick="checkOpt3Links()">
     <label for="dinShopCheck" class="css-label"></label>
</div>

The checked property is what changes the sprite using a css class.

input[type=checkbox].pinToggles:checked + label.css-label {
background-position: 0 -16px;
}

Most of this is for other functionality but thought I would show it just in case.

This is how I set up the individual checkboxes:

function checkOpt1Links(){
    $('#opt1 li a').toggleClass("inactive");

 if(opt1.getVisible() == true)
    {       
        opt1.setOptions({visible:false});
    }
    else
    {
        opt1.setOptions({visible:true});
    }
}

What I am looking for is the typical select all checkbox functionality, where if you check it the boxes all check, if you uncheck they all uncheck but also if you click a box when select all is checked the select all and the clicked checkbox uncheck and vice versa. I did look at this example: Jquery "select all" checkbox but just having difficult time making it work. Thanks for the help!

1) Use change event handler instead of click for checkbox and radio buttons.

You can make it simple like this

$('#showHideAll').on('change', 'input[type=checkbox]', function () {
    if ($('.pinToggles').is(':checked')) {
        $('.pinToggles').prop('checked', false)
    }
    else {
    $('.pinToggles').prop('checked', true)
    }
});

2) I have removed the class and onclick event handler in the below checkbox only.

HTML:

<div id="showHideAll">Show/Hide All<input type="checkbox" id="allCheck" name="pinSet" >
    <label for="allCheck" class="css-label"></label></div>
</div>

Check this JSFiddle

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