Dynamic checkBox length in java script
I am getting some values from server in XML format using ajax. The format is like :
<employees><employee><id>Id</id><employeeName>Name</employeeName></employee>.....</employees>
So to process this response i use
if(employees.childNodes.length>0){
for (loop = 0; loop < employees.childNodes.length; loop++) {
var employee = employees.childNodes[loop];
var ids = employee.getElementsByTagName("id")[0].childNodes[0].nodeValue;
var name = employee.getElementsByTagName("employeeName")[0].childNodes[0].nodeValue;
s=s+'<input name=\"userAction'+type+'\" id=\"userAction'+type+'\" value=\"'+ids+'\" type=\"checkbox"\/>'+name+'<br\/>';
}
document.getElementById('div'+type).innerHTML=s;
}
I am able to successfully show the no. of users in . But my开发者_高级运维 problem is when i click on submit function i want to know the length of no. of chekboxes. As u see i use the same name of all the checkoxes in a particular div.
var lennt=document.frm["userAction"+i].length;
alert(lennt)
If there were more than 1 user the lenght is ok, but for one user it is giving me "undefined" Please help me...
The problem you have is if there are no elements named "userAction"+i
then document.frm["userAction"+i]
is undefined
, if there is only 1 then document.frm["userAction"+i]
is a reference to one DOM node so there is no length
property, if there are > 1, document.frm["userAction"+i]
is a reference to a DOMNodeList, so there IS a length property. Solution: do some tests like so:
var checkboxes = document.frm["userAction"+i];
var lennt = 0; // default
if (checkboxes) { // checkboxes is not undefined
// assign value based on whether checkboxes.length is defined
lennt = (checkboxes.length) ? checkboxes.length : 1;
}
精彩评论