如何更改< select>来自JavaScript的价值 [英] How to change a <select> value from JavaScript

查看:74
本文介绍了如何更改< select>来自JavaScript的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,看起来很简单,但我不能说清楚。我有一个带选项列表和默认值的< select> 。用户选择一个选项并点击一个按钮后,我希望选择回到其默认值。

 < select id =select> 
< option value =defaultValue>默认值< / option>
< option value =Option1> Option1< / option>
< option value =Option2> Option2< / option>
< / select>
< input type =buttonvalue =CHANGEonclick =selectFunction()/>

因此,让我们假设用户选择选项1.我用javascript获得该值,但之后,我想要选择再次显示默认。

我发现做 document.getElementById(select)。value =defaultValue code>将不起作用。



有人知道如何将该值更改回默认值吗?

解决方案

.value 设置为其中一个选项的值适用于所有当前浏览器。在非常古老的浏览器上,您必须设置 selectedIndex

  document.getElementById(select)。selectedIndex = 0; 

如果既不是您的原始代码,也不知道您是否可能使用IE并且拥有某些东西 else 创建一个名为select的页面? (作为名称或作为全局变量?)因为 IE的某些版本有问题,它们混淆了命名空间。尝试将选择的 id 更改为fluglehorn,如果这样做,那么您就知道这是问题所在。


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?

解决方案

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.

这篇关于如何更改&lt; select&gt;来自JavaScript的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆