can anyone help me with some simple javascript please?

Discussion in 'Web Design and Development' started by jSunbeam, Jul 16, 2008.

  1. jSunbeam macrumors regular

    Joined:
    Nov 9, 2007
    #1
    This is probably a very simple thing i'm asking for help with, but (shamefully?) i've never got around to properly learning javascript - never really found myself needing/wanting to use it that much! Anyway, I've been asked to do something in javascript and i really have no idea. Any help would be hugely appreciated.

    The basic task is that i have a number of checkboxes on a page (not a set number - anywhere between one and four) and i need them to essentially behave like a radio group; only one can be selected at any one time. I guess I need some function which, upon clicking on one checkbox, automatically finds all others on the page and unselects them.

    I'm clueless with this stuff, and google is proving fruitless. Anyone?
     
  2. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #2
    If they need to act like radio boxes, why code them as check boxes? Seems counter-intuitive. It's likely why Google didn't turn up much.

    Anyways though, here's a complete solution for you. It's not an overly simplistic thing, but not hard either.

    HTML:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
            "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>Radio Checkboxes</title>
    <script type="text/javascript">
    var RadioCheckboxes = function()
    {
      checkboxes = new Array();
      Clicked = function(elt) {
        // uncheck all check boxes
        for (var x=0, y=checkboxes.length; x<y; checkboxes[x].checked=false, x++);
        // check the one clicked
        elt.checked = true;
      };
      Init = function() {
        // gather all input elements
        var inputs = document.getElementsByTagName('input');
        for (var x=0, y=inputs.length; x < y; x++) {
          // cycle through looking for checkboxes
          if (inputs[x].type == 'checkbox') {
            // when found, add to checkbox array
            checkboxes.push(inputs[x]);
            // attach event handler for being clicked
            inputs[x].onclick = function() { Clicked(this); };
          }
        }
      };
      window.onload = Init; // get things started once page loads
    }();
    </script>
    </head>
    <body>
    <ul>
      <li><input type="checkbox" name="check1" id="check1">
      <label for="check1">One</label></li>
      <li><input type="checkbox" name="check2" id="check2">
      <label for="check2">Two</label></li>
      <li><input type="checkbox" name="check3" id="check3">
      <label for="check3">Three</label></li>
    </ul>
    </body>
    </html>
    
     
  3. SrWebDeveloper macrumors 68000

    SrWebDeveloper

    Joined:
    Dec 7, 2007
    Location:
    Alexandria, VA, USA
    #3
    Here is what I use, notice the flexibility, no need to do onloads and can be easily integrated into an existing web page:

    1. Put this code between the head tags in your HTML file:

    Code:
    <script language="javascript">
    <!--//
    
    function checkAll(value, form_name, checkbox_name)
    {
      var form = document.forms[form_name];
    
      for (i = 0; i < form.length; i++)
      {
        if (form.elements[i].type == "checkbox" && form.elements[i].disabled==false && form.elements[i].name == checkbox_name)
        {
          form.elements[i].checked = value;
        }
      }
    }
    
    //-->
    </script>
    
    2. Use the following links to check/uncheck your checkboxes (add where desired in the body of your HTML page):

    HTML:
    <a href="javascript:checkAll(true, 'myform', 'mycheckboxes')">Check All Checkboxes</a> | <a href="javascript:checkAll(false, 'myform', 'mycheckboxes')">Uncheck Checkboxes</a> | 			
    
    Or...

    If you want a "toggle" checkbox which when clicked checks/unchecks the other checkboxes, instead of using the text links add in a chexkbox above the others like this:

    HTML:
    <input onClick="checkAll(this.checked,'myform','mycheckboxes')" type="checkbox" value="1" name="mytoggle"> Toggle All
    
    Notes about the JavsaScript checkAll function being called:

    Parameter 1 - use true to check, use false to uncheck
    Parameter 2 - the name of your form (i.e. in form tag, whatever "name=" is set)
    Parameter 3 - the name of the form field used for your check boxes (if using PHP append [] on the end in both the form and this parameter)

    Obviously these are examples, edit accordingly to use your form names and so on. Enjoy, and of course a quick note to angelwatt - this is just the way I do it, there are a million ways, no disrespect intended.

    -jim
     
  4. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #4
    None taken. I like my way because it makes the JavaScript unobtrusive and doesn't require editing the HTML. Using href="javascript:..." and having to add JavaScript to each checkbox input in the HTML is less appealing for me. But your way does show how things can be done differently, which is one of the reason I like doing web development, the flexibility. I do hate using the onload so often, but it's not too big of a deal and can be done so it doesn't override any other use of onload from other JavaScript libraries.
     
  5. jSunbeam thread starter macrumors regular

    Joined:
    Nov 9, 2007
    #5
    Thanks hugely for your responses guys - I'm really grateful. Will give this a try and see how i get on!
     
  6. SrWebDeveloper macrumors 68000

    SrWebDeveloper

    Joined:
    Dec 7, 2007
    Location:
    Alexandria, VA, USA
    #6
    Angelwatt's method is what you asked for exactly, as an alternative my method (toggling all) is used commonly on the Internet, such as in this forum software, actually! Just click on QuickLinks then Subscribed Threads to see it in action here.

    Users expect to be able to check one or more checkboxes, which is their purpose compared to radio buttons which involve a single choice. So using a toggle all approach is a more user friendly approach in my opinion. If you need to do it your way, that's cool, use angelwatt's code.

    Note to angelwatt:

    My method does not "add JS to each checkbox" - kindly read it again, I simply provided two methods of toggling - 1) adding text links or 2) adding a single checkbox to the top of the OP's original code. No code is changed in the OP's input tags for each checkbox.

    This is a reply just to clarify matters a bit, and expand a little on why I posted this alternative approach. Cheers to all.

    -jim
     
  7. angelwatt Moderator emeritus

    angelwatt

    Joined:
    Aug 16, 2005
    Location:
    USA
    #7
    Well, your methods involved adding JavaScript to a checkbox, or to add a link with JavaScript. My comment was trying to get at that I didn't like adding the JavaScript directly into the content area, and my method worked without editing any HTML in the content area (content area = inside body tag). It's not like I said your way was bad/wrong, I was simply adding rationale for the way I coded my solution. I did overlook that one of your methods was only adding JavaScript for a single checkbox though, so oops on that.
     

Share This Page