2013-07-31 154 views
8

我想根據是否選擇其他選項來選擇是否選擇。例如,如果有選項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> 

回答

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> 
+0

我避免做類似的東西笑。但是,謝謝你,我猜這會是那樣的! –

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>

+0

添加一些解釋並回答這個答案如何幫助OP修復當前問題 –