Ryan Harvie
Ryan Harvie

Reputation: 13

Javascript function not working with an array

i have this function which loops through an array of check boxes checking if the boxes value is equal to something in a text box, i dont know whats wrong.

function checkValue(contain)  {  
        var boxes = document.getElementsByTagName("input");  
    for (var i = 0; i < boxes.length; i++) {  
        if (boxes[i].name == "vote[]") {  
            if (boxes[i].value.indexOf(contain.value) != -1) {  
            boxes[i].checked = true;  
        }  
    }   
}  
}

and this is how i call it

 OnClick="uncheckAll(); checkValue(document.getElementsByName("countrylist"));"

this code is in side a echo in php which is like this echo ' ';

Upvotes: 1

Views: 258

Answers (4)

Chandu
Chandu

Reputation: 82903

1) Update the inlince call to use single quotes:

checkValue(document.getElementsByName('countrylist'))

2) Use document.getElementsByName to make the function little better:

function checkValue(contain)  
{           
    var boxes = document.getElementsByName("vote[]");
    for (var i = 0; i < boxes.length; i++) 
    {     
        boxes[i].checked = (boxes[i].value == contain.value);
    }   
} 

Upvotes: 0

Christa
Christa

Reputation: 485

I think your javascript might be having an issue with the name of your field being vote[].

Does it ever pass the condition:

if (boxes[i].name == "vote[]") {

Upvotes: 0

nsdel
nsdel

Reputation: 2263

You cannot nest the same type of quotes in HTML.

OnClick="uncheckAll(); checkValue(document.getElementsByName(\'countrylist\'));"

Simply escape the single quotes as shown as PHP provides an easy escape mechanism.

Upvotes: 2

Peter Perh&#225;č
Peter Perh&#225;č

Reputation: 20782

the contain argument you're passing is an array not a string. that could be the problem?

Upvotes: 0

Related Questions