SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    457
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    check a checkbox

    When a checkbox is checked, I would like a group of checkboxes on a page to be automatically checked.

    I was thinking of going about it like this:

    - value of top checkbox = check1
    - values of all checkboxes that should be automatically checked (when top checkbox is checked)= check1_1, check1_2, check1_3 etc
    - on the onclick event of the top checkbox, a piece of javascript would be executed that would iterate through all the checkboxes.

    x = 1;
    while (x < 10)
    {
    check1_(value of x).checked = true;
    x++;
    }

    How could i go about doing the above in javascript?

    Sorry for this, its jusst I dont know anythin about javascipt.

    Many thanks

  2. #2
    Awesome Addict
    Join Date
    Mar 2004
    Location
    Toronto, Canada
    Posts
    326
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    on the onclick event of the top checkbox, a piece of javascript would be executed that would iterate through all the checkboxes.
    Yes, that sounds right. Try something like:
    Code:
    window.onload = function() {
      var cbx = document.getElementById("check1");
      cbx.onclick = function() {
        if (cbx.checked) { 
          applyCheck(true);
        } else {
          applyCheck(false);
        }
      }
    }
    
    function applyCheck(bool) {
      var inputs= document.getElementsByTagName("INPUT");
      for (var x=0; x<inputs.length; x++) {
        if (inputs[x].type == "checkbox") {
            bool == true ? inputs[x].checked = true : inputs[x].checked = false;
        }
      }
    }
    So... when the page loads, get the checkbox with id "check1". If check1 is checked, check other boxes on the page otherwise uncheck. HTH....


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
  •