views:

88

answers:

3

This is surely a JS beginner question.

My issue is I want to use the value of the variable type to access the relevant checkbox; however it is treating the variable as a string. I have tried it to two ways.

function toggleGroup(type) {
    if (document.getElementById(type).checked == true){
        alert("foo");
    }
}

or

function toggleGroup(type) {
    if (document.nav.type.checked == true){
        alert("foo");     
    }
}
+4  A: 

We have no way of knowing how type should be treated - you haven't show us how the function is being called (in particular, we don't know what you are passing as its argument).

If it is a string (matching the id of an element), than document.getElementById(type).checked should work (although == true is redundant).

document.nav.type.checked should not work, because dot-notation property names are not interpolated. You have to use square bracket notation for that: document.forms.nav.elements[type].checked. This will match on name or id - if you have multiple elements with the same name, then document.forms.nav.elements[type] will be an object you can treat as an array (and won't have a checked property).

David Dorward
A: 

you can as well compare with "true"

Here Be Wolves
Comparing with the string "true" would just require additional type conversion, make the code less clear, and imply that you could compare a false value with the string "false" and get a match.
David Dorward
("true" == true) is false
Alsciende
oh, you need to use the getAttribute() method on the DOM element to use the string form "true".
Here Be Wolves
If a checked attribute is set on an element, then its value must be "checked", not "true" (browser bugs not withstanding)
David Dorward
mm hmm, right you are.
Here Be Wolves
A: 

All i need to know was the square bracket notation, like document.forms.nav.elements[type].checked.

Cheers

bertsisterwanda