0

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>
Gregory Schultz
  • 864
  • 7
  • 24

1 Answers1

0

In javascript you can only add events to elements already on the DOM. To achive what you want. you have to reassign events everytime you add a checkbox.

I would recommend adding a function that adds event listeners like so:

function setup() {

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

then calling it whenever you add a new checkbox.

Hichem Benali
  • 413
  • 3
  • 6
  • You don't 'have' to reassign events when you create new elements. The far better approach is to use a single delegated event handler. – Rory McCrossan Jun 26 '22 at 19:35
  • I was not aware that delegated events worked with all types of events. I taught that it was only applicable to generic ones like click/touch. As there no reason to use Blur or change with a div. Anyways thank you! I will edit the answer. – Hichem Benali Jun 28 '22 at 01:27