如何检查复选框是否已选中?

时间:2015-06-09 08:12:11

标签: javascript jquery

我有这个脚本,其复选框的行为类似于单选按钮:

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

我在视图中有这个循环:

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

我如何检查jquery是否以及检查了哪一个? 我试过这个但没有成功:

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

6 个答案:

答案 0 :(得分:3)

写一个change事件

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

答案 1 :(得分:0)

只需这样做。注册活动时无需使用$ .each()。

Estimator = locals()[method]

但在这种情况下,建议使用单选按钮,而不是复选框。

答案 2 :(得分:0)

有多个选项,例如jQuery $(this).prop('checked')$(this).is(':checked'),纯js this.checked,在所有给定的代码段中,它都会变为true/false

&#13;
&#13;
$(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
  });
});
&#13;
<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' />
&#13;
&#13;
&#13;

答案 3 :(得分:0)

尝试使用此

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

OR

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

答案 4 :(得分: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" />

答案 5 :(得分:-2)

您可以通过跳过for循环并允许jQuery为您完成工作来简化代码:

$(".chb").click(function(){
    $(".chb").prop('checked', false);  // uncheck all
    $(this).prop('checked', true);    // check this one you want
});