There is a data in Django DB, when html page loaded it sends request to db and create html block in Django template, and at last it insert to html by id. This part works, checkboxes creates and all is good, but there is no elements if I try to find them by id after ajax insert.
How to to get access them?
html:
<div id="fill-statuses" status-table-url="{% url 'ajax_status_data' %}"></div>
Django template:
{% for status in statuses %}
<label >
<input type="checkbox" id="{{ status.status_new }}_status_check_box">
<span >
<span >{{ status.status_new }}</span>
</span>
</label>
{% endfor %}
view.py:
def fill_status_check_boxes(request):
statuses = TaskStatus.objects.values('status_new').distinct
return render(request, 'persons/statuses_for_filter.html', {'statuses': statuses})
And now js block, with comments:
function fill_status_check_boxes() {
const url = $("#fill-statuses").attr('status-table-url')
$.ajax({
url: url,
success: function (data) {
$('#fill-statuses').html(data)
},
complete: function () {
console.log(document.querySelectorAll("[id*='status_check_box']")) //return array with elements, that's why I thought that all works, when tested it
}
})
console.log(document.querySelectorAll("[id*='status_check_box']")) //but here return empty array []
}
fill_status_check_boxes()
console.log(document.querySelectorAll("[id*='status_check_box']")) //and here also return empty array []
CodePudding user response:
$.ajax()
is executed asynchronously
So that's why your console.log
inside the complete
callback display what you're expecting, instead of the one after the ajax call.
You can create a new function to call on complete :
function fill_status_check_boxes() {
const url = $("#fill-statuses").attr('status-table-url')
$.ajax({
url: url,
success: function (data) {
$('#fill-statuses').html(data)
},
complete: handleComplete
})
}
fill_status_check_boxes()
function handleComplete() {
// Do some stuffs
console.log(document.querySelectorAll("[id*='status_check_box']"))
}