dimanche 26 juin 2022

How to check if a checkbox is checked when programmatically added? [duplicate]

Is there a way to check if a checkbox is checked when you programmatically add another checkbox? For example, if I have a function that adds a checkbox and then it's checked and then add another checkbox, the second checkbox determines if the first checkbox is selected or not. If the first checkbox is selected, don't show the second added checkbox. If the first checkbox is not selected, you can check the second checkbox and the first one is hidden.

The code I have below is suppose to hide any checkbox that's added after the first checkbox is selected.

$(document).on( "click", '.add', function() {
// programmatically add checkboxes
      $('.add').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div><div class='add2'>+add</div>").remove();
});
$(document).on( "click", '.add2', function() {
      $('.add2').after("<div id='cover_photo_set_featured'><input type='checkbox'></input>Set featured image</div>").remove();
});
// function to check is checkboxes are selected
if ($("#cover_photo_set_featured input").is(':checked')) {
    $('#cover_photo_set_featured input[type=checkbox]').each(function() {
      //Check if the box is checked
      var x = $(this).is(':checked');

      //if checkbox is NOT checked
      if(x === false) {
        //Hide the choice
        $(this).parent().hide();
      }
    });
 } else {
    $('#cover_photo_set_featured input[type=checkbox]').parent().show();
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="add">+add</div>



Aucun commentaire:

Enregistrer un commentaire