SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Select/Deselect All Checkboxes?

    First things first, Yes, I've googled this, but all sample scripts either didn't do what I was after, or the code was bad or excessive for what I needed to achieve.

    Basically, I want all check boxes in a form with the name "remove[]" to be deselected if a link is clicked (The link will be at the top of the checkbox column; it's for a shopping cart if you haven't guessed already). If the link is clocked again, I want all checkboxes to be reselected and the loop begins again.

    Can someone either point me to a good example, or possibly be generous enough to write something for?

    Just so you know, what I have in mind is a single function which is called by the onclick event. The function may rely on a global variable or something to determine if it should select or deselect all checkboxes.

    Any help is much appreciated!

  2. #2
    SitePoint Member
    Join Date
    Dec 2007
    Posts
    11
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Possible Solution

    So here it goes.

    Code JavaScript:
    var areAllChecked = false;
     
     
    function toggleAllCheckBoxes()
    {
       var objs = document.getElementsByName('remove[]');
     
       areAllChecked = ! areAllChecked;
     
       for(var i = 0; i < objs.length; i++)
       {
          objs[i].checked = areAllChecked;
       }
    }

    <a href="javascript: toggleAllCheckBoxes();">ClickMe</a>
    or
    <a href="#" onclick="toggleAllCheckBoxes();">ClickMe</a>
    or
    <button type="button" onclick="toggleAllCheckBoxes();">ClickMe</a>

    That should do it. Basically get all the checkboxes you want. Then set your global to the opposite of what it currently is. Then loop through all the objects in your array of checkboxes and set their checked property to the new value of the global. I haven't tested the code so good luck. I put three different ways to call the function. One possible issue is that some versions of IE may not use the document.getElementsByName correctly. It is possible that for IE 6 you may have to set the id of each checkbox to the same name as well (id="remove[]"). IE is great. Good luck.

  3. #3
    SitePoint Guru
    Join Date
    Oct 2006
    Location
    Queensland, Australia
    Posts
    852
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfecto!

    Works like a charm in IE6, IE7, IE8, Firefox, Safari and Opera 9 (all that I've tested), and it works flawlessly. Exactly what I was after.

    Thank you very much!

    I've got to learn javascript one of these days...


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •