Looping through form elements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • goodamr
    New Member
    • Jun 2007
    • 24

    Looping through form elements

    Hi,

    I have 10 checkboxes named chk1, chk2, chk3,.., chk10

    I'd like to loop through them, so I wrote this code but it dosen't work:

    Code:
    for (i = 1; i <= 10; i++)
    {
    	if(document.Form1.chk+i.checked == true)
    	{
    		alert("check box number: "+ i + " is checked");
    	}
    }
    Please help me! Thanks in advance.
  • RamananKalirajan
    Contributor
    • Mar 2008
    • 608

    #2
    Hi goodamr,
    Have the same name for hos checkboxes, with that u can access it easily

    ex: HTML

    Code:
    <input type="checkbox" name="chk" id="chk1" value="check1" />
    <input type="checkbox" name="chk" id="chk2" value="check1" />
    likewise for 10 check boxes.

    In JS:

    Code:
    var chkBox = document.getElementsByName("chk");
    for(var i=0;i<chkBox.length;i++){
       if(chkBox[i].checked==true)
          alert(i+" check box was selected");
    }
    Thanks and Regards
    Ramanan Kalirajan

    Comment

    • goodamr
      New Member
      • Jun 2007
      • 24

      #3
      Hi Ramanan,

      Thanks alot for your reply. I found the solution, instead of giviing the checkboxes names, I gave them id names, ex. id="chk1" . and used that code:

      Code:
      for (i = 1; i <= 10; i++)
      {
      	if(document.getElementById('chk'+i).checked == true){}
      }
      Also, I'll give your code a try.

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        you can also use names …
        Code:
        document.Form1["chk"+i].checked

        Comment

        Working...