문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top