如何设置下拉列表以在javascript中的onclick事件后选择

时间:2017-08-03 05:52:33

标签: javascript html

我有一个下拉列表,其中包含很少的选项和按钮上的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";

}

4 个答案:

答案 0 :(得分:2)

非常直接。只需按id选择输入,并将其值设置为默认值。

&#13;
&#13;
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;
&#13;
&#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)

&#13;
&#13;
<link>
&#13;
&#13;
&#13;

试试这个

答案 3 :(得分:0)

您可以将change事件附加到<select>元素,声明变量,将事件处理程序集变量设置为true,以验证是否发生了change事件。如果click值为<button>,则select .selectedIndex0 Boolean属性设为true,设为Booleanfalse

&#13;
&#13;
<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;
&#13;
&#13;