0

I have this script where checkbox behave like radio button:

$(".chb").each(function () {
    $(this).change(function () {
        $(".chb").prop('checked',false);
        $(this).prop('checked', true);
    });
});

I have this loop in view:

  @foreach (var item in Model.Banners)
   {
    <tr>
    <td style="border-right:1px solid white;border-bottom:1px solid white;padding:5px;">@Html.CheckBoxFor(m => m.PayIn.CheckedPayIn, new   {id="payin", @class = "chb" })</td>

   </tr>
   }

How can i check in jquery if and which one is checked? I tried this but no success:

if ($(this).prop("checked") == false)
    {
        alert("false");
    }
1

6 Answers 6

3

Write an on change event

$('.chb').on('change',function(){
       if($(this).is(':checked'))
       {
           //do something
       }
       else
       {
           //do something
       }
});
0

There are multiple options, like with jQuery $(this).prop('checked') or $(this).is(':checked'), with pure js this.checked, in all given snippets, it evaulate to true/false.

$(function() {
  var chbs = $('input.chb'); // cache all
  chbs.on('change', function(e){
    chbs.prop('checked', false); //un-check all
    this.checked = true; //check the current
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class='chb' type='checked' />
<input class='chb' type='checked' />
<input class='chb' type='checked' />

0

Simply do this. No need to use $.each() while you registering the event.

$('.chb').on('change',function(){
      $(".chb").prop('checked',false);
      $(this).prop('checked', true);
});

But In this scenario, radio button is much recommended than check box.

0

Try use this

if ($(this).val() == false)
{
    alert("false");
}

OR

if ($(this).attr("checked") == "false")
{
    alert("false");
}
0

$(document).ready(function() {
  $("#c1").on("change", function() {

    if ($("#c1").is(":checked")) {
      alert("checked");
    } else {
      alert("not checked");
    }

  })

})
try this,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="c1" />

-2

You can simplify your code by skipping your for loop and allowing jQuery to do the work for you:

$(".chb").click(function(){
    $(".chb").prop('checked', false);  // uncheck all
    $(this).prop('checked', true);    // check this one you want
});
1
  • he wants to check if checkbox is checked or not, and this is not an answer Commented Mar 1, 2017 at 19:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.