9

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

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

这是我的代码(我也尝试过onclick)

   <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>
4

2 回答 2

7

选项元素没有事件“onchange”,但选择元素有。

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

<script type="text/javascript">
  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;
   }
  }
 </script>
 <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>
于 2013-07-31T14:48:38.763 回答
0

<script type="text/javascript">
  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<selectElement.length; i++) {
    if(arraySelects[i] == selectedOption)
     continue; //Passing the selected Select Element

    arraySelects[i].options[selectedOption].disabled = true;
   }
  }
 </script>
 <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>

于 2017-01-15T14:58:19.913 回答