Reputation: 153
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");
}
}
Upvotes: 0
Views: 493
Reputation: 943569
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).
Upvotes: 4