JQuery Forms Checkbox Selected or Unselected All

From CoderLearner
Jump to: navigation, search

Description

Select and deselect all the checkboxes.

Example 1

  • We enable the select and deselect URL when the JS is enabled.
  • The checkbox has the name called "fruits"
<!DOCTYPE html>
<html>
    <head>
        <title>Checkbox Button</title>
        <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
        <style>
            .select_all, .unselect_all { display:none;}
            .jsEnable {display:inline}
        </style>

        <script>
            $().ready(function() {
              $('#fruit_master a.select_all,#fruit_master a.unselect_all').addClass('jsEnable');

                $('#fruit_master .select_all').click(function(e) {
                    e.preventDefault();
                    $('input[name="fruits"]').attr('checked', 'checked');
                });

                $('#fruit_master .unselect_all').click(function(e) {
                    e.preventDefault();
                    $('input[name="fruits"]').removeAttr('checked');
                });
            });
        </script>
    </head>
    <body>
        <div id="fruit_master">
            <a href="#" class="select_all">Select All</a>
            <a href="#" class="unselect_all">Unselected All</a>

            <ul>
                <li>
                    <input type="checkbox" name="fruits" value="apple" id="appleid"/>
                    <label for="appleid">Apple</label>
                </li>
                <li>
                    <input type="checkbox" name="fruits" value="banana" id="bananaid"/>
                    <label for="bananaid">Banana</label>
                </li>

                <li>
                    <input type="checkbox" name="fruits" value="coconut" id="conutid"/>
                    <label for="conutid">Coconut</label>
                </li>
                <li>
                    <input type="checkbox" name="fruits" value="mango" id="mangoid"/>
                    <label for="mangoid">Mango</label>
                </li>
                <li>
                    <input type="checkbox" name="fruits" value="Orange" id="orangeid"/>
                    <label for="orangeid">Orange</label>
                </li>
            </ul>
        </div>
    </body>
</html>