简体   繁体   English

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

[英]How to check if checkbox is checked?

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? 我该如何检查jquery中是否选中了哪一个? I tried this but no success: 我尝试了这个但没有成功:

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

Write an on change event 编写change事件

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

Simply do this. 简单地做到这一点。 No need to use $.each() while you registering the event. 注册事件时无需使用$ .each()。

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

But In this scenario, radio button is much recommended than check box. 但是在这种情况下, 单选按钮比复选框更值得推荐。

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 . 有多种选择,例如jQuery $(this).prop('checked')$(this).is(':checked') ,对于纯js this.checked js,在所有给定的代码片段中,它都有效为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' /> 

Try use this 试试这个

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

OR 要么

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

 $(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" /> 

You can simplify your code by skipping your for loop and allowing jQuery to do the work for you: 您可以通过跳过for循环并允许jQuery为您完成工作来简化代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM