select中的enable或disable选项

enable or disable option from select

本文关键字:disable 选项 enable 中的 select      更新时间:2023-09-26

我正试图根据他们是否选择了另一个选项,使一个选项可选或不可选。例如,如果有选项1-6,并且他们在第一个选择框中没有选择选项1,那么在同一个选择框和表单中的任何其他框中,则选项6不能被选择。

我环顾四周,但一切都是为了点击一个按钮来实现这一点。

这是我的代码(我也试过点击)

   <script type="text/javascript">
      function makeDisable(){
      var x=document.getElementById("mySelect2");
      x.disabled=true
      }
     function makeEnable(){
         var x=document.getElementById("mySelect2");
          x.disabled=false
     }</script>
     <form>
        <select class="mySelect" id="mySelect">
        <option onchange="makeEnable()" value="Enable list">Apple</option>
        <option onchange="makeDisable()" value="Disable list">Banana</option>
        <option id="mySelect2" disabled="true">Orange</option>
    </select>
    </form>

选项元素没有事件"onchange";,但Select元素确实如此。

我很快在下面写了一段代码。您可以添加更多选择项目。当您在其中一个选择元素中选择一个选项时,不应该在其他选择元素中的同一索引处选择选项。

function toggleDisability(selectElement) {
  //Getting all select elements
  var arraySelects = document.getElementsByClassName('mySelect');
  //Getting selected index
  var selectedOption = selectElement.selectedIndex;
  //Disabling options at same index in other select elements
  for (var i = 0; i < arraySelects.length; i++) {
    if (arraySelects[i] == selectElement)
      continue; //Passing the selected Select Element
    arraySelects[i].options[selectedOption].disabled = true;
  }
}
<form>
  <select onchange="toggleDisability(this);" class="mySelect" id="mySelect1">
    <option>Apple</option>
    <option>Banana</option>
    <option>Orange</option>
  </select>
  <select onchange="toggleDisability(this);" class="mySelect" id="mySelect2">
    <option>Hamburger</option>
    <option>Pizza</option>
    <option>Cola</option>
  </select>
</form>