Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

html - How to change a <select> value from JavaScript

I have question that seems very simple, but I just can't get it right. I have a <select> with a list of options and a default value. After the user selects an option and clicks on a button, I want the select to go back to its default value.

<select id="select">
 <option value="defaultValue">Default</option>
 <option value="Option1">Option1</option>
 <option value="Option2">Option2</option>    
</select>
<input type="button" value="CHANGE" onclick="selectFunction()" />

So lets suppose the user selects Option 1. I get that value with javascript but after that, I want the select to show again "Default".

I found that doing document.getElementById("select").value = "defaultValue" won't work.

Does anyone know how to change that value back to the default?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Setting .value to the value of one of the options works on all vaguely-current browsers. On very old browsers, you used to have to set the selectedIndex:

document.getElementById("select").selectedIndex = 0;

If neither that nor your original code is working, I wonder if you might be using IE and have something else on the page creating something called "select"? (Either as a name or as a global variable?) Because some versions of IE have a problem where they conflate namespaces. Try changing the select's id to "fluglehorn" and if that works, you know that's the problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...