根据条件选中或取消选中所有复选框

时间:2011-12-13 07:56:20

标签: jquery

我有这个HTML

   @foreach (var item in Model.Options)
  {
     <input type="checkbox" checked="checked" name="selectedObjects" noneoption=@(item.OptionText=="None of the above" ? "true" : "false") id="@(Model.QuestionNo)_@(item.OptionNumber)_chk" value="@item.OptionNumber" onchange="checkBoxChangeNone(this);" /> 
   }

我的状况

1.当用户点击复选框时,如果其中包含 noneoption = true ,则取消选中所有其他复选框。

2.当用户点击包含 noneoption = false 的复选框时,如果复选框 noneoption = true 选中它必须取消选中。

我写过这个JS,但它没有用。

        function checkBoxChangeNone(checkbox) {
        var noneoption = $(checkbox).attr('noneoption');
        var checkid = '#' + checkbox.id;
        var splitstr = checkbox.id.split('_');
        var formid = $('#myform_' + splitstr[0]); 
        if (noneoption == 'true') {
            $('input[name$=_selectedobjects]:checked').each(function () { 
                $(this).prop("checked", false);
            });
            $(checkid).prop("checked", true); 
        }

    }

2 个答案:

答案 0 :(得分:2)

这是一个JSfiddle:http://jsfiddle.net/cCqfM/1/

这是jQuery:

$("input[type=checkbox]").on("click", function() {
    if ($(this).attr("noneoption") == "false") {
        $("input[type=checkbox][noneoption=true]").attr("checked", false);
    }
    else if ($(this).attr("noneoption") == "true") {
        $("input[type=checkbox][noneoption=false]").attr("checked", false);
    }
});

答案 1 :(得分:0)

使用class对复选框进行分组,并设置如下所示的属性:

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $('input.all').click(function(){
    $('input.answer').attr("checked", "checked");
  });
  $('input.none').click(function(){
    $('input.answer').removeAttr("checked");
    $('input.all').removeAttr("checked");
  });
});
</script>
</head>
<body>
<input type="checkbox" class="answer">A. Number 1<br/>
<input type="checkbox" class="answer">B. Number 2<br/>
<input type="checkbox" class="answer">C. Number 3<br/>
<input type="checkbox" class="all">D. All<br/>
<input type="checkbox" class="none">E. None<br/>
</body>
</html>
相关问题