我有一个问题似乎很简单,但我无法做对.我有一个<select>选项列表和一个默认值.用户选择一个选项并单击按钮后,我希望select返回其默认值.
<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()" />
Run Code Online (Sandbox Code Playgroud)
因此,假设用户选择选项1.我使用javascript获取该值但在此之后,我希望select再次显示"Default".
我发现做document.getElementById("select").value = "defaultValue"不行.
有谁知道如何将该值更改回默认值?
T.J*_*der 55
设置.value为其中一个选项的值适用于所有模糊的当前浏览器.在非常旧的浏览器上,您曾经必须设置selectedIndex:
document.getElementById("select").selectedIndex = 0;
Run Code Online (Sandbox Code Playgroud)
如果没有那也不是你原来的代码工作,而且我不知道你可能会使用IE浏览器有什么别的创造了一种叫做页上的"选择"?(作为name全局变量还是作为全局变量?)因为某些版本的IE存在将命名空间混淆的问题.尝试将选择更改id为"fluglehorn",如果可行,您就知道这是问题所在.
我发现做
document.getElementById("select").value = "defaultValue"不行.
你必须经历一个单独的错误,因为这在这个现场演示中工作正常.
如果您感兴趣,这里是完整的工作代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Demo</title>
<script type="text/javascript">
var selectFunction = function() {
document.getElementById("select").value = "defaultValue";
};
</script>
</head>
<body>
<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()" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
document.getElementById("select").selectedIndex = 0 将工作
$('#select').val('defaultValue');
$('#select').change();
Run Code Online (Sandbox Code Playgroud)
这也将触发与此选择挂钩的事件
在 selectFunction() 中完成处理后,您可以执行以下操作
document.getElementById('select').selectedIndex = 0;
document.getElementById('select').value = 'Default';
Run Code Online (Sandbox Code Playgroud)