jQuery - Disable a checkbox when it's the only one checked

What’s the best way of disabling a checkbox when it’s the only one checked in jQuery? Basically, to prevent a scenario where no checkboxes are selected at all. It would need to be re-enabled when 2 or more checkboxes are checked.

My checkboxes are like this:

		<input type="checkbox" name="check1" id="check1" checked="checked"> <label for="check1">Checkbox 1</label><br />
		<input type="checkbox" name="check2" id="check2" checked="checked"> <label for="check2">Checkbox 2</label><br />
		<input type="checkbox" name="check3" id="check3" checked="checked"> <label for="check3">Checkbox 3</label><br />

Any help would be greatly appreciated :slight_smile:

does it have to be done using jquery?

if not, then you could

  1. give the <fieldset> an id

  2. use DOM methods to get the checkboxes within the <fieldset>

  3. loop thru the checkboxes and attach an onclick event handler.

  4. the event handler function in 3) then checks if at least 1 check box’s checked status is true every time one of the checkboxes is clicked.

If you are intent on using jQuery, you can do it with:

$(function () {
    $('input[name^="check"]').click(function () {
        if ($('input:checked', $(this).parent()).length === 0) {
            return false;

However, your users might become confused when they want to uncheck the only remaining checked item to then check another one.

Instead of preventing them from unchecking a checkbox (which breaks expected UI) it is advisable to instead display a warning that at least one checkbox should be selected, and to not allow form submission until at least one is selected.

Thank you both for your help.

The thing is, the page content is going to updated on the fly using AJAX. Therefore, the form wont need to be submitted. I could of course just say that there are ‘no results’ when there’s nothing selected, but thought only allowing ‘valid’ selections would be best.

Given that it is working as I’ve just described, what would you say was the best way to go about it?

A more appropriate solution is to allow the checkboxes to be unchecked while on the page, and to use validation to ensure that submission is not allowed to occur when none are checked.

It’s called validation, and can even take place before the submission occurs, so you can provide immediate feedback to someone when they uncheck the last box.

Consider, that with the current scheme when they try to untick the last box, and they’re not allowed, that this breaks everything they have learned about checkboxes from the rest of the internet. The current system is a bad user experience for all of your users that come across it.

On-the-fly feedback is a much better solution that your users know and fully understand.