519

I have a function below that I want to only trigger when a checkbox in the same tr is checked. Please tell me what I am doing wrong, the usual methods are not working. Thanks

JS

$(".add_menu_item_table").live('click', function() {
  var value_td = $(this).parents('tr').find('td.td_name').text();
  if ($('input.checkbox_check').attr(':checked')); {
    var newDiv = $('<div class="div_menu_button"></div>');
    var showDiv = $('<div id="show' + "0" + numShow++ + '" class="menu_button_info hidden"></div>');
    var toggleTrigger = $('<a id="toggleshow' + "0" + numToggle++ + '" data-target="#show' + "0" + numTarget++ + '" class="toggle_trigger actions">&nbsp;</a><div style="padding:5px"></div>');
    var menuForm = $('<form id="menu_edit_form' + "0" + numForm++ + '" class="menu_creation_form"></form>');
    $('#created_buttons_list').append(
      newDiv.text(value_td)
    );
    newDiv.wrap("<li></li>");
    newDiv.append(toggleTrigger);
    newDiv.append(showDiv);
    showDiv.append(menuForm);
    menuForm.html('<label for="navigation_label">Navigation Label</label><input id="navigation_label' + "0" + numLabelone++ + '" type="text" placeholder="Navigation Label" name="navigation_label"><label for="attribute">Attribute</label><input id="attribute' + "0" + numLabeltwo++ + '" type="text" type="text" placeholder="Attribute" name="attribute"><label for="url">URL</label><input id="url' + "0" + numLabelthree++ + '" type="text" type="text" placeholder="URL" name="url"><input type="button" value="Remove" class="button_link remove_button"> <input type="reset" value="Cancel" class="button_link">');
  }
});

var numToggle = 0;
var numShow = 0;
var numTarget = 0;
var numForm = 0;
var numLabelone = 0;
var numLabeltwo = 0;
var numLabelthree = 0;
<table width="316px" border="0" cellspacing="0" cellpadding="0" id="table-data">
  <tbody>
    <tr>
      <td width="20px"><input type="checkbox" style="width:20px;" value="1" name="checkbox"></td>
      <td width="200px"><a href="/admin/feedbackmanager/sortby/2/sortdesc/0">Page Name</a></td>
      <td width="20px"><a href="/admin/feedbackmanager/sortby/3/sortdesc/0">Add</a></td>
    </tr>
    <tr>
      <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
      <td class="td_name">Timeplot</td>
      <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
    </tr>
    <tr>
      <td><input type="checkbox" style="width:20px;" value="1" name="checkbox" class="checkbox_check"></td>
      <td class="td_name">Operations Manuals</td>
      <td><input class="add_menu_item_table" name="add_menu_item" value="Add" type="button"></td>
    </tr> 
  </tbody>
</table>
T.Todua
  • 53,146
  • 19
  • 236
  • 237
Clinton Green
  • 9,697
  • 21
  • 68
  • 103
  • `$('input.checkbox_check').checked` returns `true` if it's checked, `false` otherwise – Don Cheadle Oct 27 '15 at 14:45
  • 1
    @mmcrae, that's incorrect. The jQuery object has no property `checked`. I think you meant `$('input.checkbox_check')[0].checked` – Paul Dec 13 '16 at 18:15
  • One of those "come on jquery" moments. They could litterally write `checked: function(){return this.is(:checked)}` and be done with it. – Rager Sep 22 '22 at 18:34

11 Answers11

1285
if ($('input.checkbox_check').is(':checked')) {
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 16
    Code confirmed by jQuery doc, "the cross-browser-compatible way to determine if a checkbox is checked is to use the property: `if ( elem.checked )` or `if ( $( elem ).prop( "checked" ) )` or `if ( $( elem ).is( ":checked" ) )` ". see http://api.jquery.com/prop/ – Adriano May 19 '14 at 12:14
  • If we are going to be talking about performance then some of these comments should be added directly to the question asked by Clinton, and suggesting that the absolute fastest recommendation would be to add an ID – Tom Stickel Sep 15 '15 at 23:01
  • 1
    another possibility is simply `if ($('#my_input:checked))` – Tom Heaps Feb 12 '21 at 16:23
154

for jQuery 1.6 or higher:

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

the cross-browser-compatible way to determine if a checkbox is checked is to use the property https://api.jquery.com/prop/

Alex from Jitbit
  • 53,710
  • 19
  • 160
  • 149
  • 9
    Note that "The .prop() method gets the property value for only the first element in the matched set." see http://api.jquery.com/prop/ – Adriano May 19 '14 at 12:11
81

this $('#checkboxId').is(':checked') for verify if is checked

& this $("#checkboxId").prop('checked', true) to check

& this $("#checkboxId").prop('checked', false) to uncheck

zkanoca
  • 9,664
  • 9
  • 50
  • 94
DA001
  • 821
  • 6
  • 2
38

If none of the above solutions work for any reason, like my case, try this:

  <script type="text/javascript">
    $(function()
    {
      $('[name="my_checkbox"]').change(function()
      {
        if ($(this).is(':checked')) {
           // Do something...
           alert('You can rock now...');
        };
      });
    });
  </script>
Waiyl Karim
  • 2,810
  • 21
  • 25
16

If checked:

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

Get the checked val:

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

Get the checked val numbers:

$( "SELECTOR:checked" ).length

Check or uncheck checkbox

$( "SELECTOR" ).prop( "disabled", false );
$( "SELECTOR" ).prop( "checked", true );
  • 1
    `$( "SELECTOR:checked" ).val()` on `value="on"` gives you "on" if checked and "" if unchecked - useful! – Fanky Mar 21 '20 at 22:03
10

See main difference between ATTR | PROP | IS below:

Source: 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>
Guihgo
  • 632
  • 10
  • 13
6

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

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>
Gass
  • 7,536
  • 3
  • 37
  • 41
1

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 <script> tag, right before the </body> tag on your HTML page:

<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>
amota
  • 141
  • 8
0

to check input and get confirm by check box ,use this script...

 $(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 ...?" >
fatemeh sadeghi
  • 1,757
  • 1
  • 11
  • 14
0

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')
    ); 
});
Meloman
  • 3,558
  • 3
  • 41
  • 51
0

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
}
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51