Question

I have this piece of code:

<select name="commentselected" id="commentselected">
<option value="0">Text for Value 0</option>
<option value="1">Text for Value 1</option>
<option value="2">Text for Value 2</option>
</select>

and I was trying to use this command to change value:

document.getElementsByName('commentselected').selectedIndex[2];

but it does not work. Any idea?

Was it helpful?

Solution

getElementsByName returns an array of elements an HTMLCollection which needs to be indexed.

Also, selectedIndex is a property that needs to be set

document.getElementsByName('commentselected')[0].selectedIndex = 2;

Here's a simple demo


Also, since your select already has an id, you might as well use getElementById, like this

OTHER TIPS

As Adam said, you need to set the property and getElement*s* -- note plural -- returns an array, even if that array contains only 1 element. So, if you had more than one element named "commentselected', to get to your select you would have had to loop through the array and search for a 'type=select' ... not a very effective bit of code

If you need to access 1 element, you use getElementById ... that is why the ID property is unique, to make sure there is only one element with that id.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top