我有一个下拉列表,其中包含很少的选项和按钮上的onclick事件,在从下拉列表中选择并单击按钮之后,如何将下拉列表设置为由JavaScript选择的默认值。
<select id="userType">
<option value="Select" disabled selected
id="myDefault">Select</option>
<option value="1">Games</option>
<option value="2">Movies</option>
</select>
<button type="button" name="button"onclick="addOption()">Send</button>
function addOption(){
if (userType.value === "Select") {
alert("Please select correct option");
}
else{
console.log(userType.options[userType.selectedIndex].value);
}
document.getElementById('userType').value = "Select";
}
答案 0 :(得分:2)
非常直接。只需按id选择输入,并将其值设置为默认值。
function addOption(){
// Do stuff...and then:
document.getElementById('userType').value = "Select";
}
&#13;
<select id="userType">
<option value="Select" disabled selected
id="myDefault">Select</option>
<option value="1">Games</option>
<option value="2">Movies</option>
</select>
<button type="button" name="button"onclick="addOption()">Send</button>
&#13;
答案 1 :(得分:1)
这是您的工作代码:
$("button").click(function() {
$('select').prop('selectedIndex', 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="userType">
<option value="Select" disabled selected
id="myDefault">Select</option>
<option value="1">Games</option>
<option value="2">Movies</option>
</select>
<button type="button" name="button">Send</button>
答案 2 :(得分:1)
<link>
&#13;
试试这个
答案 3 :(得分:0)
您可以将change
事件附加到<select>
元素,声明变量,将事件处理程序集变量设置为true
,以验证是否发生了change
事件。如果click
值为<button>
,则select
.selectedIndex
将0
Boolean
属性设为true
,设为Boolean
到false
。
<script>
var changed, select;
function addOption() {
if (changed) {
select.selectedIndex = 0;
changed = false;
}
}
onload = function() {
select = document.getElementById("userType");
select.onchange = function() {
changed = true;
}
}
</script>
<select id="userType">
<option value="Select" disabled selected
id="myDefault">Select</option>
<option value="1">Games</option>
<option value="2">Movies</option>
</select>
<button type="button" name="button" onclick="addOption()">Send</button>
&#13;