user898763452
user898763452

Reputation: 169

Array element as a parameter for getElementById().checked

I'm having trouble referencing a checkbox element from an array of element ids. Why can I reference it using a literal and string var as the parameter of getElementById, but not by using an element of an array?

<html>
<body>

<ul id="zip_wrapper">
<li><label><input type="checkbox" id="72002" value="72002" name="zip_codes[]" checked="checked">72002</label></li>
<li><label><input type="checkbox" id="72034" value="72034" name="zip_codes[]" checked="checked">72034</label></li>
</ul>
<script>

var zips = "";
var tester = "72034";
zips = document.getElementById("zip_wrapper").innerText.split(" ");

//zips =  Array.prototype.slice.call(zips); //a la http://stackoverflow.com/questions/4287681/extremely-annoying-javascript-array-object-error

document.write("zips array, tokenized by split(\" \"): " + zips + "<br />");

document.write("document.getElementById(\"72034\").checked: " + document.getElementById("72034").checked + "<br />");
document.write("document.getElementById(tester).checked: " + document.getElementById(tester).checked + "<br />");
document.write("document.getElementById(zips[1]).checked: " + document.getElementById(zips[1]).checked + "<br />");

</script>
</body>
</html>

You can see the page in action here: https://dl.dropbox.com/u/1634015/website/checked.html

Upvotes: 0

Views: 4327

Answers (2)

Peter
Peter

Reputation: 1

The argument must be a string literal e.g.

wanted=document.getElementById("myhtmlobject").value

so if you have an array of similar objects rather than just one,

myhtmlobject[1]
myhtmlobject[2]
myhtmlobject[3]
myhtmlobject[4]
etc

then reference them like this

myobj="myhtmlobject[" + j + "]"
wanted= document.getElementById(myobj).value

Upvotes: 0

CWSpear
CWSpear

Reputation: 3270

When I go to your test page, when I do

zips = document.getElementById("zip_wrapper").innerText.split(" ");

in the console, I'm getting zips as an element of length one, so zips[1] would be undefined. It seems (at least in Chrome) that innerText is returning each one on its own line. I split by \n and I got:

["72002", "72034", ""]

I think the bottom line is the issue isn't that you're using an element from an array, but that you array isn't made up like you are expecting it to be.

And as Pointy pointed out, it seems that Firefox just returns undefined and I found Chrome to return them on each their own line (i.e. separated with "\n" with an empty string at the end).

You might need a different approach to what you're trying to accomplish, but the answer to the original question, is that there's nothing wrong with using an array element as a parameter of getElementById.

Upvotes: 1

Related Questions