0

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

谢谢。

4

1 回答 1

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/

于 2012-08-09T03:56:55.270 回答