简体   繁体   中英

Adding a class with jQuery to parent element of a checkbox when that is clicked and the checkbox is hidden

I have a list designed to look like toggle buttons, but they're actually a checklist of preferences. As such, the input is hidden and I want to have a class added to the parent label if the checkbox is checked.

It all works great, except for in IE8 which isn't happy. I think this may be the .change, but I can't quite work out how to achieve this with .click, my attempts have ended unsuccessfully.

FIDDLE HERE!

HTML

<li>
    <label class="checkbox">
        <input type="checkbox" data-toggle="checkbox" />
        <span class="btn-flat">Option</span>
    </label>
</li>

JS

$('.checkbox input').change(function() {
    if (this.checked) {
        $(this).parent('.checkbox').addClass('checked');
        $(this).attr('checked','checked');
    }else {
        $(this).parent('.checkbox').removeClass('checked');
        $(this).removeAttr('checked');
    }
});

So, if this is checked, check it ?

if (this.checked) {
    $(this).attr('checked','checked');
}

doesn't make much sense, why not just :

$('.checkbox input').on('change', function() {
    $(this).parent('.checkbox').toggleClass('checked', this.checked);
});

and never ever remove the checked attribute, set it to false with .prop('checked', false); or this.checked = false

try adding $(this).parent().children('.btn-flat').addClass('grey'); to the if block and $(this).parent().children('.btn-flat').removeClass('grey'); to the else block of the javascript and then add .checkbox .grey{background-color: #ccc;} to css file. This way it targets the specific html element.

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