0

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?

Tushar S
  • 352
  • 1
  • 6
  • 15
  • Possible duplicate of : http://stackoverflow.com/questions/14778364/select-all-checkboxes-using-jquery Also, this fiddle: http://jsfiddle.net/NogginBox/ScnQT/1/ – Sajal May 28 '16 at 18:59

1 Answers1

1

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

<html>

<form>
    <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>
</form>

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

<script>
    // event handler for when an item with the 'selectAll' is changed
    $(".selectAll").change(function(){
        // 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"));
    });
</script>

</html>
BizzyBob
  • 12,309
  • 4
  • 27
  • 51
  • Hmm thanks @BizzyBob, does this handle the scenario where clicking on any other option unselects the 'all cateory' option? – Tushar S May 28 '16 at 21:04
  • 1
    it does not. but you could copy the existing one and make some minor changes... :-) – BizzyBob May 28 '16 at 21:21