提问者:小点点

MVC中复选框的jquery代码


这个jQuery函数在alert(isChecked)中总是返回true,即使在未选中时也是如此:
请注意。AccrualCheckbox是Div的类名,而不是为复选框设置的类。我删除了if($(this).prop('check','check'))的代码,现在它总是返回为'false'

$('.accrualCheckbox').click(function () {
    var isChecked = $(this).attr('checked') ? true : false;
    alert($(this).attr('checked'));
    alert(isChecked);
    if ($(this).prop('checked', 'checked')) {
        var parentDiv = $(this).parents('.searchLine');
        $(parentDiv).css('border', '1px solid red');

        //Checkbox
        $(parentDiv).find("input[type=text]").each(function () {
            $(this).val('B');
            $(this).prop('disabled', true);
        });
    }
});
});

我将复选框保留在div:

<div class="accrualCheckbox">
    @Html.CheckBox("chkSalesAndMarketing")
</div>   

共2个答案

匿名用户

您需要使用prop()而不是attr(),或者还可以执行以下操作:

var isChecked = $(this).is(':checked');

但是这个if($(this).prop('check','check'))将始终返回true,因为您在条件中将值设置为checked

更新我假设这是您想要做的:

$('.accrualCheckbox :checkbox').click(function () {
    if ($(this).is(':checked')) {  // or $(this).prop('checked');
        var parentDiv = $(this).closest('.searchLine');
        $(parentDiv).css('border', '1px solid red');
        //Checkbox
        $(parentDiv).find(":text").each(function () {
            $(this).val('B');
            $(this).prop('disabled', true);
        });
    }
});

匿名用户

使用$(this).prop('checked')代替attr()

请参阅“属性与属性”部分:http://api.jquery.com/prop/