Kenro
Kenro

Reputation: 33

Looping through a checkbox array that has one element

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";
    }

Upvotes: 2

Views: 17417

Answers (4)

Kevin Boucher
Kevin Boucher

Reputation: 16675

You want radio buttons.

<input type='radio' name='tags' value='[whatever]' />

You won't have to 'check and make sure only one is selected'. And to get the

var tags = document.getElementsByName('tags'),
    value = '', i = 0;

for( ; i < tags.length; i++ )
{
    if( tags[i].checked ) {
        value = tags[i].value;
        break;
    }
}

Upvotes: 2

nirazul
nirazul

Reputation: 3955

Why do you need Checkboxes? Wouldn't this be a great opportunity to use Radiobuttons?

Upvotes: 4

Eli Gassert
Eli Gassert

Reputation: 9763

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) .....
}

Upvotes: 2

bas
bas

Reputation: 628

from the top of my head... if there is only one checkbox selected it might be document.form1.tags is not an array...

Upvotes: -1

Related Questions