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:
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.