Chakradhar
Chakradhar

Reputation: 773

check or uncheck all checkboxes based on a condition

I have this 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);" /> 
   }

My condition

1.when a user click on a checkbox if its contain noneoption=true then all other checkboxes are unchecked.

2.When a user click on checkbox that contain noneoption=false if a checkbox with noneoption=true checked it must unchecked.

i have written this JS but its not working.

        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); 
        }

    }

Upvotes: 1

Views: 5162

Answers (2)

ericccs
ericccs

Reputation: 66

use class to group the checkboxes, and set the attributes like below:

<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>

Upvotes: 0

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

Here's a JSfiddle: http://jsfiddle.net/cCqfM/1/

Here's the 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);
    }
});

Upvotes: 2

Related Questions