如何在组合中选择第一个值

how to select the first value in a combo

本文关键字:选择 第一个 组合      更新时间:2023-09-26

我的html中有一个组合,有时我必须使用JavaScript将值更改为第一个。

enter code here
   <select  name="myCombo" id="myCombo">
     <option value="1">first option</option>;
     <option value="2">second option</option>;
     <option value="3">third option</option>;
     <option value="4">Other</option>;
  </select> 
   // resetCombo('myCombo')

还有一个以组合作为参数的 JavaScript 函数:

function resetCombo(combo) {
      document.getElementById(combo).value =  document.getElementById(combo).get_items().getItem(0);
 }

但它不起作用。哪种方法是正确的?

将方法更新为

function resetCombo(combo) {
   document.getElementById(combo).selectedIndex =0;
}

试试这个,

function resetCombo(combo) {
      document.getElementById(combo).value =  document.getElementById(combo).options[0].value;
 }

试试这个:

function resetCombo(combo) {
      document.getElementById(combo).value = document.querySelector('#' + combo + ' option:nth-child(1)').value;
 }
document.getElementsByTagName('button')[0].onclick = function() {
  resetCombo('myCombo');
}
<select name="myCombo" id="myCombo">
  <option value="1">first option</option>;
  <option value="2">second option</option>;
  <option value="3">third option</option>;
  <option value="4">Other</option>;
</select>
<button>reset</button>