Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6
  1. #1
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts

    validate checkbox group

    Hi, I currently generate from a template some checkboxes
    <input type="checkbox" id="machines[{UM_ID}]" name="machines[{UM_ID}]" value="{UM_ID}" />

    which may give say ..

    <input type="checkbox" id="machines[2]" name="machines[2]" value="2" />
    <input type="checkbox" id="machines[19]" name="machines[19]" value="19" />
    <input type="checkbox" id="machines[1]" name="machines[1]" value="1" />

    how would I validate that at least 1 checkbox has been checked with javascript? .. does the id need to be "machines" or rather machines[$num] , and either way has anyone got a pointer to a quick validation script (preferably using getElementById not forms[element_$x].blah)

    I could set the id to machines_$x etc but I don't want to have to pass all that data to javascript if possible, just give it the `group` name and let it do the rest.
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #2
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,274
    Thanks
    28
    Thanked 271 Times in 265 Posts
    I believe that would use something like the following code.

    Note that I ran into some errors with some characters in your ID names; the W3C validator was indicating that the left square bracket ([) character isnít permitted in ID names. I even tried encoding it as &#x5b; and it still said that the character isnít permitted. Thatís something to keep in mind if you still need to have IDs on your check boxes (which I removed in the below code).

    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
      <head>
    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="Author" content="Patrick Garies"/>
        <title>XHTML 1 Strict Document</title>
    
        <style type="text/css">
          html { padding: 1em; }
          body { margin: 0; }
          fieldset { padding: 0.5em; text-align: center; }
        </style>
    
        <script type="text/javascript">
          <!--//--><![CDATA[//><!--
    
          function validate() {
            var input = document.getElementsByTagName("input");
            for (var i = 0; i < input.length; i++) {
              if (input[i].checked == true) {
                alert("Your input has been received.\nThank you!");
                i = input.length - 1;
                }
              else if (i < input.length - 1) ;
              else alert("You have not made at least one selection.\nPlease do so before proceeding.");
              }
            }
    
          //--><!]]>
        </script>
    
      </head>
      <body>
    
        <fieldset>
          <label><input type="checkbox" value="2"/> 2</label>
          <label><input type="checkbox" value="19"/> 19</label>
          <label><input type="checkbox" value="1"/> 1</label>
          <input type="submit" value="Submit" onclick="validate();"/>
        </fieldset>
    
      </body>
    </html>
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #3
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    Hi , I appreciate the input, my problem is this is part of a larger form and there are other unrelated checkboxes so I need some way to say, `validate this checkbox group`

    At worst I can give the checkboxes individual id's and pass all those to the validation script but I assumed there must be some common method for this type of validation ? or to iterate though a `group`

    PS, are you saying name="checkbox[1]" is not valid ? or just id="checkbox[1]" ?
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #4
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,040
    Thanks
    10
    Thanked 92 Times in 90 Posts
    OK, with a bit more googling you got me on the right path, all I needed to do was wrap the checkboxes in a div and iterate through that using your example.

    Code:
    function is_checked(divname){
    	group=document.getElementById(divname);
    	var box = group.getElementsByTagName("input");
    	for (var i=0;i<box.length;i++) {
    		if(box[i].checked == true){
    			return true;
    		}
    	}
    	return false;
    }
    cheers.
    Last edited by firepages; 12-12-2006 at 02:01 PM.
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #5
    Regular Coder martin_narg's Avatar
    Join Date
    Jul 2002
    Location
    Chamonix, France
    Posts
    600
    Thanks
    1
    Thanked 3 Times in 3 Posts
    Yeah mate, you can enclose all your checkboxes in a parent element, but I'd be inclined to check that you're iterating through checkboxes. Also it's good practice to get in the habit of declaring all local variables explicitly in javascript:
    Code:
    function is_checked(parentID){
    	var inputs = document.getElementById(parentID).getElementsByTagName("input"),
    		found = false;
    	
    	for(var i=0, len=inputs.length; i<len; i++) {
    		if(inputs[i].getAttribute("type").toLowerCase() == "checkbox" && inputs[i].checked) {
    			found = true;
    			break;
    		}
    	}
    	
    	return found;
    }
    Hope this helps

    m_n
    Last edited by martin_narg; 12-12-2006 at 03:21 PM.
    "Cos it's strange isn't it. You stand in the middle of a library and go 'Aaaaaaaaaaaaaaaaggggggghhhhhhh!'
    and everybody just stares at you. But you do the same in an aeroplane, and everybody joins in."
    -Tommy Cooper

  • #6
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,274
    Thanks
    28
    Thanked 271 Times in 265 Posts
    Quote Originally Posted by firepages View Post
    PS, are you saying name="checkbox[1]" is not valid ? or just id="checkbox[1]" ?
    I was saying that the left square bracket character is not valid in an ID attribute. The name attribute allows more characters than the ID attribute does, but since the name and ID attributes must be identical, youíre effectively limited to the characters allowed by the ID attribute. Thus, while name="checkbox[1]" is probably valid by itself, you canít have that if youíre also going to have an ID attribute, since the values must be equivalent.

    It probably does makes sense that itís invalid though since it would cause problems with CSS attribute selectors, which themselves use square brackets. For example, in CSS, *#checkbox[1] would be the same as selecting an element with the ID checkbox and the attribute 1; of course, that makes no sense either since attributes canít begin with numbers. The result would be that the selector would select nothing even if an element (erroneously) with id="content[1]" existed.

    Quote Originally Posted by martin_narg View Post
    Yeah mate, you can enclose all your checkboxes in a parent element, but I'd be inclined to check that you're iterating through checkboxes.
    Thatís not really necessary. If you use the fieldset element (as in my example) to mark up related groups of form elements, then you can assume that all elements in that fieldset element are check boxes; or you can look at the document source and make sure, at the least. You can use a div element as well, as I believe firepages said he did, but the fieldset element would probably be more semantically correct.
    Last edited by Arbitrator; 12-16-2006 at 07:50 PM. Reason: another reply
    For every complex problem, there is an answer that is clear, simple, and wrong.


  •  

    Posting Permissions

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