简体   繁体   中英

Have at least on checkbox in checkbox group visually(!) checked

I'm looking for a way to have in a group of checkboxes at least on checkbox checked. The only things i could find was methods to validate IF at least one checkbox is checked, but you where always able to check/uncheck the last checkbox - is there a way to make sure, when the user clicks the checkboxes that at least one checkbox has to remain checked (and only if at least two checkboxes are checked one of both can be unchecked) ?

Thanks for your help! Vin

Checkboxes 'change' in value, so it's probably best to listen for that. Remember 'click' would only handle mouse clicks, so one could still change the val w/ enter or spacebar. For accessibility, i'd stick with onchange.

Fiddle

Updated Fiddle

js

$(function () {
    $('.cbClassSegments').on('change', function (e) {

        !$(this).siblings(':checked').length &&
            $(this).prop('checked', true) &&
                e.preventDefault();

        // move assignment down and prevent default action 
        cbObjSegments[this.id] = this.checked;
        console.log(valuesTrueInObject(cbObjSegments));

    })
})

html

<input type="checkbox" value="1" checked>
<input type="checkbox" value="1">
<input type="checkbox" value="1">

Try the following:

$('input[type="checkbox"]').click(function(event) {
    var atLeastOneIsChecked = $('input[name="name"]:checked').length;

    if(atLeastOneIsChecked<1){ 
           event.preventDefault();
    }
});

have a look at this fiddle

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