IT Certificaions

Google Cloud Platform

Wednesday, November 30, 2011

multiple checkboxes with same id


Handling multiple checkboxes with same id's


If suppose you have defined more than one checkboxes with sdame id's, then it will treat it as an array of names.

<form name="CheckBoxForm">


<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="Checkbox" name="myCheckbox" id="myCheckbox"  />
<input type="" onclick="testCheckboxes()" />
</form>


Now according to HTML, id must be unique. So here it will treat them like an array. So if you want to access them, do as
given here,


function testCheckboxes(){
var myCheckboxArray= new Array();
var total=document.getElementsByName('myCheckbox').length;
for(var i=0;i<total;i++){
 alert(document.getElementsByName('myCheckbox')[i].checked);
 if(document.getElementsByName('checkbox')[i].checked == true){
 myCheckboxArray[myCheckboxArray.length]="Checked";
 }
    }

}