Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  113] [ 4]  / answers: 1 / hits: 17167  / 12 Years ago, thu, november 8, 2012, 12:00:00

I have a list of dynamically created checkboxes named tags which I loop through with javascript to make sure only 1 is checked and to get the value. If for some reason this list of checkboxes only has 1 item, my script won't look at it. When I alert the tag's length I get undefined.



    var total=[];
for (var i=0; i < document.form1.tags.length; i++){
if(document.form1.tags[i].checked==true){
total.push(document.form1.tags[i].value);
}
}

if(total.length==0){
alert(Please select a product to edit.);
}else if (total.length>1){
alert(Please select only one product to edit.);
}else{
document.location = go somewhere;
}

More From » forms

 Answers
45

Two suggestions:




  1. use getElementsByName instead to get all the elements so you can iterate them:


  2. Use a framework like jquery. Any reason you can't use jquery or another framework? Your life would be so much easier.




var tags = document.getElementsByName('tags');
for(var i = 0; i < tags.length; ++i)
{
if(tags[i].checked) .....
}

[#82094] Wednesday, November 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
;