2012-11-15 52 views
0

在下面的例子中,當您選擇選項id="chocolate-yes"和/或id="vanilla-yes"id="icecreamcone-yes"也將所選擇的選項:

製作選擇不可點擊,當條件滿足

<ul id="icecream" style="list-style:none;line-height:30px;"> 
    <li> 
    <select id="icecreamcone"> 
     <option value="addicecreamcone">Would you like an ice cream cone?</option> 
     <option id="icecreamcone-yes" value="yes">Yes</option> 
     <option id="icecreamcone-no" value="no">No thanks</option> 
    </select> 
    </li> 
    <li> 
    <select id="vanilla"> 
     <option value="addvanilla">Would you like to add vanilla ice cream?</option> 
     <option id="vanilla-yes" value="yes">Yes</option> 
     <option id="vanilla-no" value="no">No thanks</option> 
    </select> 
    </li> 
    <li> 
    <select id="chocolate"> 
     <option value="addchocolate">Would you like to add chocolate ice cream?</option> 
     <option id="chocolate-yes" value="yes">Yes</option> 
     <option id="chocolate-no" value="no">No thanks</option> 
    </select> 
    </li> 
    <li> 
    <select id="sprinkles"> 
     <option value="addsprinkles">Would you like to add sprinkles on top?</option> 
     <option id="sprinkles-yes" value="yes">Yes</option> 
     <option id="sprinkles-no" value="no">No thanks</option> 
    </select> 
    </li> 
</ul> 


<script type="text/javascript"> 
function observeFlavor(flavor, requires) { 
    document.getElementById(flavor).onchange = function(){ 
     if(document.getElementById(flavor).options[1].selected == true) { 
     document.getElementById(requires).options[1].selected = true 
     } 
    } 
} 

observeFlavor("chocolate","icecreamcone"); 
observeFlavor("vanilla","icecreamcone"); 
</script> 


In包含上面的腳本,沒有人知道如何在id="vanilla-yes",id="chocolate-yes"或兩者都選中時使<select id="icecreamcone">不可點擊,但是當它們都被取消選擇時,<select id="icecreamcone">將再次可點擊?


注意:不使用禁用屬性。

回答

2

相信這應該這樣做:

<script type="text/javascript"> 
function observeFlavor(flavor, requires) { 
    document.getElementById(flavor).onchange = function(){ 
     if(document.getElementById(flavor).options[1].selected == true) { 
     document.getElementById(requires).options[1].selected = true; 
     document.getElementById(requires).disabled = true; 
     } 
     else{   
     document.getElementById(requires).disabled = false; 
     } 
    } 
} 

document.getElementById("your-submit-button").onclick = function() {  
    document.getElementById("icecreamcone").disabled = false; 
} 

observeFlavor("chocolate","icecreamcone"); 
observeFlavor("vanilla","icecreamcone"); 
</script> 
+0

這工作,但只有一個問題:窗體域結果將不被髮送到服務器。有沒有辦法讓這個字段在不禁用的情況下無法點擊? – Macchiato

+0

然後在提交之前,將元素設置爲disabled = false; (「your-submit-button」)。onclick = function(){ document.getElementById(「icecreamcone」)。disabled = false; } – HerrWalter

+0

你能編輯代碼來反映你的更新嗎? – Macchiato