简体   繁体   中英

detecting if a checkbox is ticked inside a target div with jQuery

I have the following markup, below the closing span tag is a number list items.

<div class="header_block">
   <span class="background_flag_container">
      <input id="block_background" type="checkbox" name="block_background">
      <span class="background_flag_text">Has Banner Background</span>
   </span>
   ...
</div>

This is my jQuery. What I am looking to do is check if the one and only checkbox, with a name of 'block_background' is checked. There are a number of 'block_background' checkboxes on the page, but there will only ever be one within $(this) which is the .header_block div.

$(this).find(".background_flag_container input:checkbox[name='block_background']").each(function(){
   if ($(this).checked) {
      console.log('is checked');
   }
});

How can I check if it's checked?

You can use is(':checked') to check if something is selected

   $(this).find(".background_flag_container input:checkbox[name='block_background']").each(function(){
       if ($(this).is(':checked')) {
          console.log('is checked');
       }
    });

Although seeing that the checkbox has the id block_background which should be unique. You could just do this:

if ($('#block_background').is(':checked')) {
    console.log('is checked');
}
$("input#block_background]").is(':checked')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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