Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
PHP jQuery Cookbook

You're reading from   PHP jQuery Cookbook jQuery and PHP are the dynamic duo that will allow you to build powerful web applications. This Cookbook is the easy way in with over 60 recipes covering everything from the basics to creating plugins and integrating databases.

Arrow left icon
Product type Paperback
Published in Dec 2010
Publisher Packt
ISBN-13 9781849512749
Length 332 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Vijay Joshi Vijay Joshi
Author Profile Icon Vijay Joshi
Vijay Joshi
Arrow right icon
View More author details
Toc

Table of Contents (17) Chapters Close

PHP jQuery Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Handling Events with jQuery FREE CHAPTER 2. Combining PHP and jQuery 3. Working with XML Documents 4. Working with JSON 5. Working with Forms 6. Adding Visual Effects to Forms 7. Creating Cool Navigation Menus 8. Data Binding with PHP and jQuery 9. Enhancing your Site with PHP and jQuery Firebug Index

Creating the select/unselect all checkboxes functionality


This is a frequently-used feature of web applications. A group of checkboxes exists on a page, which can be controlled by a single checkbox. Clicking on the master checkbox selects all checkboxes and unchecking it deselects all.

We will create the functionality to toggle checkboxes in this recipe. We will also learn how to get values for checked elements using jQuery's selectors.

Getting ready

Make sure you have the jQuery library ready to be used.

How to do it...

  1. Create a new file in the chapter1 directory and name it as checkbox.html.

  2. Let us design the page first. Create an unordered list and apply some CSS to it. The first item in this list will be a checkbox that will work as a handle to toggle other checkboxes. Then create other items in the list: names of books each having a checkbox before it. All these checkboxes have the same class name toggle. Create another list item consisting of a button that will be used to display the selected books. Finally, create a last list item and assign an ID to it. We will use it to display selected book names.

    <html>
      <head>
        <title>Select/Unselect Checkboxes</title>
        <style type="text/css">
        ul { background-color:#DCDCDC; list-style:none; margin:0pt;padding:0pt; width:350px;}
        li { padding:10px; }
        </style>
      </head>
      <body>
        <ul>
          <li>
            <input type="checkbox" id="handle">
            <label for="handle"><strong>Toggle All</strong></label>
          </li>
          <li>
            <input type="checkbox" class="toggle"/>
            <label>A Study in Scarlet</label>
          </li>
          <li>
            <input type="checkbox" class="toggle"/>
            <label>The Sign of the Four</label>
          </li>
          <li>
            <input type="checkbox" class="toggle"/>
            <label>The Adventures of Sherlock Holmes</label>
          </li>
          <li>
            <input type="checkbox" class="toggle"/>
            <label>The Valley of Fear</label>
          </li>
          <li>
            <input type="checkbox" class="toggle"/>
            <label>His Last Bow</label>
          </li>
          <li><input type="button" id="getValue" value="Get Selected Values"/></li>
          <li id="selected"></li>
        </ul>
      </body>
    </html>
  3. Running the checkbox.html file in browser will display the following screen:

  1. To bring this page to life include the jQuery library and attach event handlers to the checkboxes. The first event handler will be attached to the first checkbox, which will take care of selecting and deselecting all other checkboxes. The second one will be attached to individual checkboxes. It will select/deselect the main handle depending on whether all checkboxes are checked or not. The last event handler is for the input button that will display the selected values beneath it.

    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $(document).ready(function()
      {
        $('#handle').click(function(){
          if($(this).attr('checked') == true)
            $('.toggle').attr('checked', 'true');
          else
            $('.toggle').removeAttr('checked');
        });
    
        $('.toggle').click(function(){
          if($('.toggle:checked').length == $('.toggle').length)
            $('#handle').attr('checked', 'true');
    
          if($('.toggle:checked').length < $('.toggle').length)
            $('#handle').removeAttr('checked');
          
        });
        
        $('#getValue').click(function(){
          var values = '';
          if($('.toggle:checked').length)
          {
            $('.toggle:checked').each(function(){
              values+= $(this).next('label').html() + ' ,';
            });
            $('#selected').html('Selected values are: ' + values);
          }
          else
            $('#selected').html('Nothing selected');
        });
      });
    </script>
  2. Now, refresh your browser and start playing with the checkboxes. Clicking on the Toggle All checkbox will select and deselect all the checkboxes alternatively. Click on the Get Selected Values button and a comma-separated list will appear below the button displaying names of all selected books.

How it works...

On clicking the Toggle All checkbox we check if it is selected or not. If it is selected, we select all the other checkboxes having the class toggle using the class selector and set their checked attribute to true, which selects all the checkboxes. On the other hand, if it is not selected we remove the checked attribute from all checkboxes that makes all of these deselected.

We will have to take care of another issue here. If all the checkboxes are selected and any one of them is deselected, the handler checkbox should also get deselected. Similarly, if all checkboxes are selected one by one, the handler checkbox should also get checked. For this we attach another event handler to all the checkboxes having class toggle. The .toggle:checked selector selects all those elements that have class toggle and those which are also selected. If the length of the selected elements is equal to the total number of checkboxes, we can conclude that all are selected and hence we select the handler checkbox too.

If the number of selected elements is less than the total number of checkboxes then we remove the checked attribute of the handler checkbox to deselect it.

There's more...

Using selectors

In the previous example we used .toggle:checked to select all the checkboxes that have class toggle and are checked. : is a selector that is used to filter a set of elements. Listed below are examples that demonstrate how it can be used to filter elements.

$('div:first').click(function()
{
  //do something
});

The above code will select the first DIV on the page and will add a click event handler to it.

$(p:gt(2)').hide();

gt stands for greater than. It accepts a 0-based index and matches elements that have an index greater than the one specified. If a page has 5 p elements, the above example will hide p numbers 3 and 4. Remember that the index is 0-based.

You can read about all the selectors on the jQuery site at this URL: http://api.jquery.com/category/selectors/.

You have been reading a chapter from
PHP jQuery Cookbook
Published in: Dec 2010
Publisher: Packt
ISBN-13: 9781849512749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image