• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 295
  • Last Modified:

select.options as associative array

I want to access the select.options collection as an associative array, but can't seem to get it to work, e.g.

<select>
<option id="option1" value="nar">blah
</select>
<script>
refToSelect.options["option1"].value= "hello";
</script>

As just about everything in JavaScript is an associative array, I thought this would work, but it doesn't.

Any ideas on how to make it work (and don't tell me to loop through the options and match - thats what I want to avoid).

Leon
0
Astroman
Asked:
Astroman
  • 4
  • 4
1 Solution
 
knightEknightCommented:
document.getElementById("option1").value
0
 
knightEknightCommented:
<script>
document.getElementById("option1").value = "hello";
</script>
0
 
AstromanAuthor Commented:
I know that strictly that works, but I'd prefer (from a code readability point of view) to reference it via the options, or at least the select object, so it's clear what the code is doing.

I guess I could do it using the children collection of select?

Cheers,

Leon
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
knightEknightCommented:
yes, perhaps:

refToSelect.children.option1.value = "hello";
0
 
AstromanAuthor Commented:
I'll leave this a bit longer, but I guess this is the best way. If so, I'll give you the points.  Thanks kek.

0
 
AstromanAuthor Commented:
Dunno what to do now. Turns out my original post was correct, but my (SS generated) code had the element id as a number, which is wrong and was breaking it.

So the answer is, 'options' is an associative array (as I suspected), and I'm silly.

I'll give you the points, because someone should have them, and at least it got me debuggin it properly....
0
 
knightEknightCommented:
I see, I thought that it should have worked as you originally described it, but I just assumed not since you had tried it.  Oh well, thanks for the points, and for the exercise.
0
 
AstromanAuthor Commented:
actually, I'm beginning to feel a complete fool. Having ( I thought) verified that it did actually work, it seems to have stopped working now.  I dunno. type first, think later today.

'children' works for sure, anyway, so I'm happy (ish)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now