jQuery,一旦值存储在新部分中,就禁用输入

时间:2012-08-09 03:54:02

标签: jquery

我有2个选择列表mySelect和mySelect2。 如果选中一个,如果单击复选框,则另一个同时更改。

请检查以下代码:

<!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,以便在值到位后您无法对任何更改进行任何更改?

感谢。

1 个答案:

答案 0 :(得分:6)

当你没有使用任何问题时,不确定为什么你的问题被标记为“jQuery”,但仍然:

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

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

disabled设置回false以重新启用控件。

以下是使用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/