在更改时影响复选框属性

时间:2015-07-22 20:58:00

标签: c# jquery .net asp.net-mvc

目的是检查两个字段(用户名和密码)是否输入了文本,如果是,请选中复选框,如果没有,请取消选中该复选框。

如果我在两者中输入文本,它都有效。如果我删除用户字段中的文本,则取消选中;但是,如果我在用户字段中重新输入一个字符,则该框将不会重新检查。可能会发生什么?

<div class="controls"> 
    @Html.CheckBoxFor(model => model.checkboxId, new Dictionary<string, object> { { "disabled", "disabled" } })
</div>

<script type="text/javascript">
 $(document).ready(function() {
    $('#Username, #Password').change(function () {
        var username = $('input#Username').val();
        var password = $('input#Password').val();
        if (username.length != 0 && password.length != 0) {
            $('#checkboxId').attr('checked', true);
        }
        else {
            $('#checkboxId').removeAttr('checked');
        }
    });
</script>

2 个答案:

答案 0 :(得分:2)

要使用jQuery选中和取消选中复选框输入,请使用$().prop("checked",true)$().prop("checked",false)。只需删除checked属性不会取消选中该复选框,但prop()功能会取消选中。

答案 1 :(得分:0)

您正在删除该属性,因此无法再将其设置为true。

相反,您应该使用prop() ...

$('#Username, #Password').change(function () {
        var username = $('input#Username').val();
        var password = $('input#Password').val();
        if (username.length != 0 && password.length != 0) {
            $('#checkboxId').prop('checked', true);
        }
        else {
            $('#checkboxId').prop('checked',false);
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="Username" placeholder="Username">
<input type="text" id="Password" placeholder="Password">
<input type="checkbox" id="checkboxId">