Hwende
Hwende

Reputation: 649

Javascript change selectedIndex of a Select by its name

I'm using a wordpress plugin which forces me to use the name="" attribute. So I can't change it to id="" or class="". When I click the button I want the selectedIndex for name="select" to be changed to 2.

Here's what I've tried:

<select name="select">
<option value="1">option1</option>
<option value="2">option2</option>
</select>
<input type="button" value="CHANGE" onclick="selectFunction()" />

var selectFunction = function() {
document.getElementById("select").selectedIndex = 2;
};

So I basically want to use this function using name="" and not id="". Which means something like document.getElementById("select").selectedIndex = 2; wont work.

Thanks in advance!

Upvotes: 0

Views: 570

Answers (2)

nnnnnn
nnnnnn

Reputation: 150030

You can use querySelector() to select with a CSS style selector:

document.querySelector('select[name="select"]').selectedIndex = 2;

Demo: http://jsfiddle.net/4exeJ/

Or if you needed to support old versions of IE that don't have querySelector() you could use document.getElementsByTagName("select") and then loop through the resulting list testing the .name of each until you found the right one.

Or there's the document.getElementsByName() function, which also returns a list (or an HTMLCollection), but according to QuirksMode.org it doesn't work properly in IE<=9.

Note that option indexes start at 0 (so in your example you don't want to set selectedIndex to 2 because the last option is index 1).

Upvotes: 4

Krish R
Krish R

Reputation: 22711

Try this, You can use getElementsByName

<select name="select">

Javascript:

document.getElementsByName("select")[0].selectedIndex = 1;

Upvotes: 1

Related Questions