0

I have 3 checkboxes and want to see that which checkbox is checked [vice-versa]. If Group1 is checked then it should return Group1:true and vice versa.

  @Html.CheckBoxFor(m => m.Group1, new { @class = "chk",@id= "Group1" })                
  @Html.CheckBoxFor(m => m.Group2, new { @class = "chk", @id = "Group2"})               
  @Html.CheckBoxFor(m => m.Group3, new { @class = "chk", @id = "Group3"})

Script

   $('.chk').change(function () {  
         var id = $(this).val();          
          $('#' + id).is(":checked");
        });
3
  • Looks to me like you're missing a closing ' after the .chk selector. Is that a copy error? Commented May 30, 2018 at 23:24
  • @RyanGibbs, It is fixed. Yes that was copy error. Commented May 30, 2018 at 23:40
  • it should return Group1:true Where do you want to return to? Commented May 31, 2018 at 0:07

2 Answers 2

1

You can accomplish this all by using the $(this) object within your change listener. Here's a sample of how to do that:

$('.chk').change(function () {          
    console.log($(this).attr('id') + ":" + $(this).is(':checked'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' id='Group1' class='chk'>
<input type='checkbox' id='Group2' class='chk'>
<input type='checkbox' id='Group3' class='chk'>

Here we grab the attribute 'id' to get the id of the control that was changed and then concatenate that with the result of .is(':checked'). Of course in my example I'm just console.logging the result, but you could return or do whatever you need to do with it.

Hope that helps.

Sign up to request clarification or add additional context in comments.

Comments

1

If you wanted more information on the state of the other checkboxes following the event, you could use (with comments):

$(function () {
    $(".chk").on("change", function () {
        var eventId = $(this).attr("id");
        // checked or unchecked for change event
        if ($(this).is(":checked")) {
            console.log("=> " + eventId + " has been checked");
        } else {
            console.log("=> " + eventId + " has been unchecked");
        }

        // Iterate all checkboxes
        $.each($(".chk"), function () {
            var id = $(this).attr("id");
            if (id !== eventId) {
                if ($(this).is(":checked")) {
                    console.log("=> " + id + " is checked");
                } else {
                    console.log("=> " + id + " is not checked");
                }
            }
        });
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.