简体   繁体   中英

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!

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).

Try this, You can use getElementsByName

<select name="select">

Javascript:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM