Web Analytics Made Easy -
StatCounter Identifying checkbox ids - CodingForum

Announcement

Collapse
No announcement yet.

Identifying checkbox ids

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Identifying checkbox ids

    Hi.

    I have a list of checkboxes with Ids that go something like;

    chk_AGE=16
    chk_AGE=17
    chk_AGE=18
    chk_GENDER=MALE
    chk_GENDER=FEMALE
    chk_RANK=OFFICER
    chk_RANKE=OTHER


    When a user checks/unchecks '16' (for example), I want javascript to look up how many checkboxes in my form have an Id that begins with "chk_AGE" and return the number in an alert box ("3" in this case).

    If my user had checked/unchecked "Officer" an alert box would return "2" as there are 2 checkboxes that begin "chk_RANK".

    Can someone please help with this? I am a complete javascript beginner.

  • #2
    Originally posted by Mike1985 View Post
    Hi.

    I have a list of checkboxes with Ids that go something like;

    chk_AGE=16
    chk_AGE=17
    chk_AGE=18
    chk_GENDER=MALE
    chk_GENDER=FEMALE
    chk_RANK=OFFICER
    chk_RANKE=OTHER
    I don't understand that. So the checkbox is something like this?
    Code:
    <input type="checkbox" id="chk_AGE=16" />
    If yes, this would be illegal. A "=" must not be part of an id attribute. If no ... at least this is what you said ...
    Last edited by devnull69; Sep 12, 2011, 09:47 AM.

    Comment


    • #3
      Not very clear what do you understand by id... Can you provide a relevant fragment of your HTML code, please?
      Last edited by Kor; Sep 12, 2011, 09:50 AM.
      KOR
      Offshore programming
      -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

      Comment


      • #4
        I take it to mean that those parts before the "=" sign are the IDs and the input's value is what the OP has listed after the "=" sign.

        So first I would set straight that there should not be more than one instance of an ID in a single page (if my assumption above is correct). You should append a number to each checkbox input's ID (or use some other way of giving them a unique ID while still keeping the same first characters for their ID for use in your javascript). Something like chk_AGE_0, chk_AGE_1, chk_AGE_2 would work fine. These can all have the same name, but the IDs should be unique. Same idea for gender, rank, and any other things you may add.

        With that done, look at the "indexof" method for some help. I think you will basically want to use something like this:

        Code:
        //first, we collect all input elements in the page...
        var all_inputs=document.getElementsByTagName('input');
        //then, we set up an array to use to populate with only the elements we care to work with...
        var relevant_inputs=new Array();
        //now we cycle through all of our elements and add them to the "relevant" array if they BEGIN with the string we specify...
        for(i=0;i<all_inputs.length;i++){
        	if(all_inputs[i].id.indexOf('chk_AGE')==0){
        		relevant_inputs.push(all_inputs[i]);
        	}
        }
        //we now have an array of elements that begin with, in this case, "chk_AGE"
        //if we only want the length of the array (number of relevant input items) we just refer to relevant_inputs.length
        alert(relevant_inputs.length);
        If you wanted to put that into a function you could do something like this:
        Code:
        function alert_count(id_snippet){
        	//first, we collect all input elements in the page...
        	var all_inputs=document.getElementsByTagName('input');
        	//then, we set up an array to use to populate with only the elements we care to work with...
        	var relevant_inputs=new Array();
        	//now we cycle through all of our elements and add them to the "relevant" array if they BEGIN with the string we specify...
        	for(i=0;i<all_inputs.length;i++){
        		if(all_inputs[i].id.indexOf(id_snippet)==0){
        			relevant_inputs.push(all_inputs[i]);
        		}
        	}
        	//we now have an array of elements that begin with the stated value of id_snippet
        	//if we only want the length of the array (number of relevant input items) we just refer to relevant_inputs.length
        	alert(relevant_inputs.length);
        }
        Then, use an onclick event to trigger the function with the appropriate id snippet (beginning part of the ID that you want to test for) and you're done.

        Note that this function ONLY tests for IDs that BEGIN WITH the string you provide.

        If you want to do less manual coding you could set up the function and the onclick event to reference the name rather than the ID, and only test for other elements with a name that exactly matches the name of the element that was clicked, but I'm not sure if that's what you're wanting to do (or if your checkboxes for each group all have the same name, which they might not). Too much to guess at for now, I suppose.
        The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
        See Mediocrity in its Infancy
        It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
        Seek and you shall find... basically:
        validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

        Comment


        • #5
          Apologies. Here is a little snippet of HTML;

          Code:
          <li class="pureCssMenui"><a class="pureCssMenui" href="#"><input type='checkbox' id='chk_AGE=16' name='chk_AGE=16' value='AGE=16' checked><label for='chk_AGE=16'>16</label><BR></a></li>
          <li class="pureCssMenui"><a class="pureCssMenui" href="#"><input type='checkbox' id='chk_AGE=17' name='chk_AGE=17' value='AGE=17' checked><label for='chk_AGE=17'>17</label><BR></a></li>
          <li class="pureCssMenui"><a class="pureCssMenui" href="#"><input type='checkbox' id='chk_AGE=18' name='chk_AGE=18' value='AGE=18' checked><label for='chk_AGE=18'>18</label><BR></a></li>
          The whole id for each checkbox has been joined together with PHP from a table. The "AGE" represents the Field and the "16","17" etc is the Field Value. I put the "=" sign in there so I knew when the Field part ended and where the Values began.

          Thanks all for your help so far. Rowsdower! Yes I would like my script to use variables instead of hard-coded "AGE" in the Javascript. Is that possible?

          getElementsByTagName sounds like just the thing I'm looking for. This is one of main struggles with Javascript. I don't know the function names

          I'll study the code you have replied with and see if I can get it to work..

          Mike

          Comment


          • #6
            You should use radio buttons in groups, not checkboxes. A user can not be the same time male and female, 17 or 18 years old, can she/he?

            Thus you can give them a common name (within the same group), and give them different values.
            KOR
            Offshore programming
            -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

            Comment


            • #7
              Aha, I see. Then devnull69's post should be adhered to. IDs and names cannot use the "=" character. As for Kor's suggestion - that is also perfectly true.

              All-in-all, I would switch to radio buttons with the same name for each group and with separate IDs for each input. Then we can simplify the javascript to something like this:

              Code:
              function alert_count(element_name){
              	//get all elements with the specified name...
              	var relevant_inputs=document.getElementsByName(element_name);
              	//we now have an array of elements with the stated value of element_name
              	//if we only want the length of the array (number of relevant input items) we just refer to relevant_inputs.length
              	alert(relevant_inputs.length);
              }
              Then you only need to pass the clicked element's name to the function call and you're done. Depending on whether you use inline javascript or unobtrusive javascript this will look a little different to actually implement. The unobtrusive javascript approach is what will (among other things) minimize your manual coding, if that is what you are looking for. To do that, you will initialize the event handlers for each relevant element on page load and DOM completion.
              The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
              See Mediocrity in its Infancy
              It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
              Seek and you shall find... basically:
              validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting

              Comment


              • #8
                Kor - it's not a user registration form. It's a filters feature that searches through a list of people. So a user may want to look for all the males, females or both.

                I think giving them a common 'Name' though is a very good idea. I did not know you could identify a specific checkbox by it's Name (although now I type it, it sounds obvious!)

                Comment


                • #9
                  I had a friend help me and this seems to do the trick..

                  Code:
                  <script type="text/javascript">
                  function checkBoxes(fieldValues)
                  {
                  //get the tag name for what was clicked
                  var tagName = document.getElementsByTagName("input");
                  var howMany = 0;
                  	
                  	// for every time i is less than however many boxes there are with the same tag name...
                  	for (var i = 0; i < tagName.length; i++)
                  	{
                  	// if it's a checkbox, and tagname's name is = to what was clicked's tag name then...
                  	if (tagName[i].type == "checkbox" && tagName[i] && (tagName[i].name == fieldValues.name)) 
                  	// add 1 to check
                  	howMany++;
                  	}
                  alert("Total Count: " + howMany);
                  
                  return howMany; 
                  
                  }
                  </script>
                  And I had to modify the HTML slightly

                  Code:
                  <li class="pureCssMenui"><a class="pureCssMenui" href="#"><input type='checkbox' id='chk_AGE=16' name='chk_AGE' value='AGE=16'
                   checked onclick=" checkBoxes(this);"><label for='chk_AGE=16'>16</label><BR>
                  </a></li>
                  Thanks for all your help. I'm sure I'll be back soon!!

                  Comment

                  Working...
                  X
                  😀
                  🥰
                  🤢
                  😎
                  😡
                  👍
                  👎