Verify dynamically created checkbox

0

Good afternoon.

I need to check if a dynamically created checkbox (is within a modal) is checked. As it was created dynamically, I thought of the following code:

$(document).ready(function () {
   $(document).on('click', '#elemento', function () {
      if($(document).on("input[id='elemento']:checked")) {
         alert('Sim');
      } else {
         alert('Não');
      }
   });
});

The problem is that this function always returns true. I can not use this.checked because it will reference the document, not the checkbox. I can not understand what's wrong. Anyone have any ideas?

    
asked by anonymous 27.11.2017 / 16:25

1 answer

1
The problem is that the code $(document).on("input[id='elemento']:checked") will not return the value of checkbox , but if the #elemento element exists in document , and therefore if will always return true.

To check checkbox , change if to:

if($(this).is(":checked")) {

Looking like this:

$(document).ready(function () {
   $(document).on('click', '#elemento', function () {
      if($(this).is(":checked")) {
         alert('Sim');
      } else {
         alert('Não');
      }
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" id="elemento" checked="checked" />
    
27.11.2017 / 17:22