Tushar S Tushar S - 4 months ago 7x
jQuery Question

How can I let a user choose EITHER one option or many of the other ones?

I have a bunch of options in a form for the user to select. The way the options should work is as follows:

  • Either the user selects the 'All categories' option.

  • OR the user can select one or more of the other options.

So basically I want the clicking of the 'All categories' option to remove the selection on all other options, and I want the selection of options other than 'All categories' to unselect the 'All categories' option.
Currently, all of these options are checkboxes, but I'm open to changing them.

I'm guessing I'll need to use some sort of jQuery/Javascript for this behavior.
Any ideas?


Just create a simple event handler for the .change() event of the checkboxes and set the 'checked' property:


    <p><input type="checkbox" name="option[]" class="selectAll"> Select All</p>
    <p><input type="checkbox" name="option[]" class="option"> Option 1</p>
    <p><input type="checkbox" name="option[]" class="option"> Option 2</p>
    <p><input type="checkbox" name="option[]" class="option"> Option 3</p>

    <button type="submit">Submit</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    // event handler for when an item with the 'selectAll' is changed
        // set the 'checked' property of items with the 'option' class
        // to have the same value as the 'selectAll' checkbox
        $(".option").prop('checked', $(this).prop("checked"));