jQuery(如果选中复选框)

jQuery if checkbox is checked

提问人:Clinton Green 提问时间:11/1/2011 最后编辑:Mateen UlhaqClinton Green 更新时间:10/17/2023 访问量:1362051

问:

我在下面有一个函数,我只想在选中相同的复选框时触发。tr

$(".add_menu_item_table").live('click', function() {
  if ($('input.checkbox_check').attr(':checked')); {
    // I want this to trigger.
  }
});
<table id="table-data">
  <tbody>
    <tr>
      <td><input type="checkbox" class="checkbox_check"></td>
      <td><input type="button" class="add_menu_item_table" value="Add"></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="checkbox_check"></td>
      <td><input type="button" class="add_menu_item_table" value="Add"></td>
    </tr> 
  </tbody>
</table>

jQuery 复选框 if-statement

评论

0赞 Don Cheadle 10/27/2015
$('input.checkbox_check').checked如果选中,则返回,否则返回truefalse
1赞 Paul 12/14/2016
@mmcrae,这是不正确的。jQuery 对象没有属性。我想你的意思是checked$('input.checkbox_check')[0].checked
0赞 Rager 9/23/2022
那些“来吧jquery”的时刻之一。他们可以乱扔垃圾并完成它。checked: function(){return this.is(:checked)}

答:

1294赞 SLaks 11/1/2011 #1
if ($('input.checkbox_check').is(':checked')) {

评论

16赞 Adriano 5/19/2014
jQuery文档确认的代码,“确定是否选中复选框的跨浏览器兼容方法是使用属性:或或”。查看 api.jquery.com/propif ( elem.checked )if ( $( elem ).prop( "checked" ) )if ( $( elem ).is( ":checked" ) )
0赞 Tom Stickel 9/16/2015
如果我们要谈论性能,那么其中一些评论应该直接添加到克林顿提出的问题中,并建议绝对最快的建议是添加一个 ID
1赞 Tom Heaps 2/13/2021
另一种可能性很简单if ($('#my_input:checked))
154赞 Alex from Jitbit 4/21/2014 #2

对于 jQuery 1.6 或更高版本:

if ($('input.checkbox_check').prop('checked')) {
    //blah blah
}

用于确定是否选中复选框的跨浏览器兼容方法 是使用属性 https://api.jquery.com/prop/

评论

9赞 Adriano 5/19/2014
请注意,“.prop() 方法仅获取匹配集合中第一个元素的属性值 api.jquery.com/prop
82赞 DA001 12/21/2016 #3
  • 验证是否选中了它

    $('#checkboxId').is(':checked')
    
  • 要检查

    $("#checkboxId").prop('checked', true)
    
  • 取消选中

    $("#checkboxId").prop('checked', false)
    
10赞 Guihgo 12/24/2016 #4

查看 ATTR 之间的主要区别 |道具 |如下

来源:http://api.jquery.com/attr/

$( "input" )
  .change(function() {
    var $input = $( this );
    $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +
      ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +
      ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );
  })
  .change();
p {
    margin: 20px 0 0;
  }
  b {
    color: blue;
  }
<meta charset="utf-8">
  <title>attr demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>
 

 
</body>
</html>

38赞 Waiyl Karim 2/27/2017 #5

如果上述解决方案都因任何原因而不起作用,就像我的情况一样,请尝试以下方法:

  <script type="text/javascript">
    $(function()
    {
      $('[name="my_checkbox"]').change(function()
      {
        if ($(this).is(':checked')) {
           // Do something...
           alert('You can rock now...');
        };
      });
    });
  </script>
16赞 user6830821 11/28/2018 #6

如果选中

$( "SELECTOR" ).attr( "checked" )  // Returns ‘true’ if present on the element, returns undefined if not present
$( "SELECTOR" ).prop( "checked" ) // Returns true if checked, false if unchecked.
$( "SELECTOR" ).is( ":checked" ) // Returns true if checked, false if unchecked.

获取检查值:

$( "SELECTOR:checked" ).val()

获取选中的 val 编号:

$( "SELECTOR:checked" ).length

选中或取消选中复选框

$( "SELECTOR" ).prop( "disabled", false );
$( "SELECTOR" ).prop( "checked", true );

评论

1赞 Fanky 3/22/2020
$( "SELECTOR:checked" ).val()如果选中,则为您提供“打开”,如果未选中,则为您提供“” - 有用!value="on"
0赞 fatemeh sadeghi 10/14/2020 #7

要检查输入并通过复选框进行确认,请使用此脚本...

 $(document).on("change", ".inputClass", function () {
    if($(this).is(':checked')){
     confirm_message = $(this).data('confirm');
       var confirm_status = confirm(confirm_message);
                        if (confirm_status == true) {
                           //doing somethings...
                         }
                   }});  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >

1赞 amota 6/21/2021 #8

New to jQuery/Javascript and tried the above solutions. Eventually, this is what worked for me to:

  1. keep elements hidden upon loading page (because checkboxes = unchecked by default), and then
  2. have elements show/hide based on whether the checkbox is checked or not.

It's probably a little ugly/redundant/extraneous syntax-wise, but it works for now!


Note: this all goes in the following tag, right before the tag on your HTML page:<script></body>

<script type="text/javascript">
   // 'solution code' goes here...
</script>

'solution code':

    $(document).ready(function(){

          // HIDE ELEMENTS UPON PAGE LOAD (CHECKBOX = UNCHECKED)
          if ($([id="show_box"]).is(':checked') == false)
                $("#hiddenDiv").hide();

          // SHOW/HIDE ELEMENTS VIA CHECKBOX STATUS
          $('[id="show_box"]').change(function()
          {
            if ($(this).is(':checked'))
                $("#hiddenDiv").fadeIn();
            else
                $("#hiddenDiv").fadeOut();
          });

    });
  • [id="show_box"] (the checkbox, with id 'show_box')
  • #hiddenDiv (the id of the element I want to hide/show)
  • this (since it's nested, it ends up representing 'show_box')

And here is the HTML code on the page, which the 'solution code' is referring to:

<!-- CHECKBOX -->
<input type="checkbox" id="show_box" name="box" value="">

<!-- ELEMENT THAT SHOWS/HIDES -->
<div id="hiddenDiv"></div>
8赞 Gass 8/22/2021 #9

You can use the method which returns true if an element is checked, otherwise it returns false..is(':checked')

Example

$('input').on('click', function(){
  isChecked = $(this).is(':checked')
  
  if(isChecked){ 
    $('html').css('background-color','green')
  }
  else{ 
    $('html').removeAttr('style')
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="checkbox"> Try me </label>

0赞 Meloman 3/21/2022 #10

I needed to know this property to automatically check/uncheck "sub-checkboxes" and this is working :

jQuery('.checkbox-parent').click(function(){
    jQuery('.checkbox-child').prop(
        'checked', 
        jQuery('.checkbox-parent').prop('checked')
    ); 
});
0赞 Du-Lacoste 12/16/2022 #11

Following can be done in both JavaScript and jQuery which is pretty simple.

var getVal=$('#isAgeSelected').is(":checked"); // jQuery

var getVal=document.getElementById("isAgeSelected").checked //JavaScript

if (getVal==true) {
// do something
} else {
// do something
}