2012-08-09 16 views
0

我有2個選擇列表mySelect和mySelect2。 如果點擊複選框選中其中一個,則另一個同時改變。jQuery,一旦值被存儲在新的部分,禁用輸入

請檢查下面的代碼:

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript"> 

function displayResult() { 
    if(document.form1.billingtoo.checked == true) { 
     var x = document.getElementById("mySelect").selectedIndex; 
     // Set selected index for mySelect2 
     document.getElementById("mySelect2").selectedIndex = x; 
    } 
} 

</script> 
</head> 
<body> 

<form name="form1"> 
Select your favorite fruit: 
    <select id="mySelect"> 
     <option>Apple</option> 
     <option>Orange</option> 
     <option>Pineapple</option> 
     <option>Banana</option> 
    </select> 

    <br> 

    <input type="checkbox" name="billingtoo" onclick="displayResult()"> 

    <br> 

Select your favorite fruit 2: 
    <select id="mySelect2"> 
     <option>Apple</option> 
     <option>Orange</option> 
     <option>Pineapple</option> 
     <option>Banana</option> 
    </select> 

</form> 
</body> 
</html> 

...我怎麼禁用(變灰)mySelect2所以,你不能做任何修改,一旦值的任何變化都到位?

謝謝。

回答

6

不知道爲什麼你的問題,當你不使用任何,但仍然被標記「jQuery的」:

// with "plain" JS: 
document.getElementById("mySelect2").disabled = true; 

// with jQuery 
$("#mySelect2").prop("disabled", true); 

無論哪種方式設置disabledfalse重新啓用的控制。

這裏有很多方式使用jQuery來重寫你的函數之一:

$(document).ready(function() { 
    // bind the checkbox click handler here, 
    // not in an inline onclick attribute: 
    $('input[name="billingtoo"]').click(function() { 
     var $mySelect2 = $("#mySelect2"); 
     // if checkbox is checked set the second select value to 
     // the same as the first 
     if (this.checked) 
      $mySelect2.val($("#mySelect").val()); 
     // disable or re-enable select according to state of checkbox: 
     $mySelect2.prop("disabled", this.checked); 
    }); 
}); 

演示:http://jsfiddle.net/nnnnnn/99TsC/

+0

我怎麼會再次啓用,如果沒有選中該複選框使用JS的版本? – avidaicu 2012-08-09 04:25:10

+0

正如我上面所說的,將'disabled'屬性設置回'false':'document.getElementById(「mySelect2」)。disabled = false;' – nnnnnn 2012-08-09 04:45:43

相關問題