Clinton Green
Clinton Green

Reputation: 9977

jQuery if checkbox is checked

I have a function below that I want to trigger only when a checkbox in the same tr is checked.

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

Upvotes: 535

Views: 1420581

Answers (11)

DA001
DA001

Reputation: 951

  • To verify if it is checked

    $('#checkboxId').is(':checked')
    
  • To check

    $("#checkboxId").prop('checked', true)
    
  • To uncheck

    $("#checkboxId").prop('checked', false)
    

Upvotes: 94

Gass
Gass

Reputation: 9344

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>

Upvotes: 9

Du-Lacoste
Du-Lacoste

Reputation: 12757

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
}

Upvotes: 0

Meloman
Meloman

Reputation: 3712

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')
    ); 
});

Upvotes: 0

amota
amota

Reputation: 331

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>

Upvotes: 1

fatemeh sadeghi
fatemeh sadeghi

Reputation: 2573

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 ...?" >

Upvotes: 0

user6830821
user6830821

Reputation:

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 );

Upvotes: 16

Waiyl Karim
Waiyl Karim

Reputation: 2950

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>

Upvotes: 38

Guihgo
Guihgo

Reputation: 652

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>

Upvotes: 10

Alex from Jitbit
Alex from Jitbit

Reputation: 60566

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/

Upvotes: 155

SLaks
SLaks

Reputation: 887305

if ($('input.checkbox_check').is(':checked')) {

Upvotes: 1312

Related Questions