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");
    }
None
  • 8,817
  • 26
  • 96
  • 171
  • 1
    possible duplicate of [Check if checkbox is checked with jQuery](http://stackoverflow.com/questions/2204250/check-if-checkbox-is-checked-with-jquery) – Sudhanshu Saxena Jun 09 '15 at 08:13

6 Answers6

3

Write an on change event

$('.chb').on('change',function(){
       if($(this).is(':checked'))
       {
           //do something
       }
       else
       {
           //do something
       }
});
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
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.

Tuhin
  • 3,335
  • 2
  • 16
  • 27
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

Try use this

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

OR

if ($(this).attr("checked") == "false")
{
    alert("false");
}
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
Osama AbuSitta
  • 3,918
  • 4
  • 35
  • 51
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" />
user786
  • 3,902
  • 4
  • 40
  • 72
-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
});
silver
  • 650
  • 4
  • 15