0

everyone!

I have a problem with handling dynamically created checkboxes, that created through JQuery func.

At first i tried handling checkboxes that were initialized together with the DOM - it's work great.

But I need handle checkboxes that created with JQuery in initialized form.

This is source html code, that in which we insert new checkboxes:

<div class="input-box-wrapper">
        <div class="box" id="part1">
            <form id="forma">
                <input type="submit">
            </form>  
        </div>
</div>

JQuery func for create new checkboxes:

$('#forma').submit(function(e) {
        e.preventDefault();
        let checkboxDiv = document.getElementById("forma");
        checkboxDiv.innerHTML = '';
        for (let i = 0; i < 3; i++) {
            let label = document.createElement("label")
            let checkBox = document.createElement("input")

            checkBox.type = "checkbox"
            checkBox.className = "checkbox"
            checkBox.value = "Prog Lang"
            checkBox.id = "checkbox-" + i;
            checkBox.name = "checkbox";
            
            checkboxDiv.appendChild(label)
            label.appendChild(checkBox);
            label.appendChild(document.createTextNode(i))
        }
    })

JQuery func for handling new checkboxes:

$('#forma input[type=checkbox]').on('click', function(e){
        let checkboxes = document.querySelectorAll('.checkbox')
        let resultList = []
        for (let checkbox of checkboxes) {
            if (checkbox.checked == true) {
                resultList.push(checkbox.value)
            }
        }
        console.log(resultList)
        $.ajax({
            url: 'rest',
            type: 'POST',
            dataType: 'json',
            data: {
                'status': 'OK',
                'list': resultList,
                'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            success: function (response) {
            },
            error: function (response) {
            }
        });
     });

HTML code after inserting new checkboxes:

enter image description here

I read that the .click() function is not suitable for handling dynamically created objects and in this regard, I changed it to .on() As a result, .on() doesn't work for me. What can be done in this case? Thank you in advance.

  • It's much simpler to create elements with jQuery, and you're already using it anyway. – Pointy Jan 30 '23 at 16:08
  • 1
    Also see: [jQuery - Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – Yogi Jan 30 '23 at 16:19
  • Yogi, thank you very much! I read this article and everything worked out for me. I switch from - $('#forma input[type=checkbox]').on('click', function(e) {} to $('#forma').on('click', 'input', function(e) {} – 1v5a3g5 Jan 30 '23 at 17:20

0 Answers0