启用或禁用select中的选项

时间:2013-07-31 14:30:44

标签: javascript html-select

我试图根据他们是否选择其他选项来选择或不可选择。例如,如果有选项1-6并且他们没有在第一个选择框中选择选项1,那么在该SAME选择框和表单中的任何其他框中,则无法选择选项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>

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

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