On为<选项>选择等效项

OnSelect equivalent for <option>?

本文关键字:选择 选项 On      更新时间:2023-09-26

我有一个<select>标签,我希望它在选择选项时更改隐藏输入的值。我想用这个:

<input type=hidden value=Ineedtochangethis name=asdf>
<select><option onselect="stuff()">Option 1 is selected</option>...</select>

然后这个

function stuff() {
document.getElementsByName("asdf").value=opt1slct;
}

当然,这是行不通的。我该怎么做才能获得类似的效果?

please check following code:  
  <select onChange="jsFunction()" id="selectOpt">
        <option value="1" >1</option>
        <option value="2">2</option>
        <option value="3">3</option>
    </select>
    function jsFunction(){
      var myselect = document.getElementById("selectOpt");
      if(myselect.options[myselect.selectedIndex].value == 1){
          alert('hide');
      }else{
           alert('show');
      }
    }

通过使用 select 元素的 selectedIndex 属性(也可能是options属性)。

<input id="yourHiddenField" type="hidden"/>
<select onchange="stuff(this);">
  <option>Option 1 is selected</option>
</select>

而 JavaScript:

function stuff(yourSelectElement){
  document.getElementById('yourHiddenField').value = yourSelectElement.options[yourSelectElement.selectedIndex].innerHTML;
}

如果您只想在隐藏字段中存储一个数字,请在option标签上使用 value 属性,如下所示:

<option value="1">Option 1 is selected</option>

然后 JS 像这样变化:

document.getElementById('yourHiddenField').value = yourSelectElement.options[yourSelectElement.selectedIndex].value;