I have set up a checkbox that should appear with each row in the list. I would like to pass row.id and boolean based on checkbox state. But the problem is that it only works for the first checkbox: id and boolean state is passed.
JavaScript
x
11
11
1
{% for row in list %}
2
.
3
<label>
4
Off
5
<input name="active{{ row.id }}" id="active{{ row.id }}" type="checkbox" list_id="{{ row.id }}">
6
<span class="lever"></span>
7
On
8
</label>
9
.
10
{% endfor %}
11
I have added javascript to listen to checkbox state and after checking, send a POST request to Flask app. It works but it only fires when the first checkbox is checked, all other checkboxes generated by Jinja2 are ignored.
JavaScript
1
24
24
1
document.addEventListener('DOMContentLoaded', function () {
2
var checkbox = document.querySelector('.input[type="checkbox"]');
3
checkbox.addEventListener('change', function () {
4
var list_id = $(this).attr('list_id');
5
6
if (checkbox.checked) {
7
req = $.ajax({
8
url : '/dashboard',
9
type : 'POST',
10
data : { id: list_id, active : 'true' }
11
});
12
13
console.log(list_id);
14
} else {
15
req = $.ajax({
16
url : '/dashboard',
17
type : 'POST',
18
data : { id : list_id, active: 'false' }
19
});
20
console.log(list_id);
21
}
22
});
23
});
24
Advertisement
Answer
- You only get the first when you use querySelector
- you have a dot in front of the input that should not be there
- You have jQuery, so use it – it will take all checkboxes in one go without the need for
querySelectorAll
JavaScript
1
14
14
1
$(function() {
2
$('input[type="checkbox"]').on('change', function() {
3
var list_id = $(this).attr('list_id');
4
console.log(list_id);
5
req = $.ajax({
6
url: '/dashboard',
7
type: 'POST',
8
data: {
9
id: list_id,
10
active: this.checked ? 'true' : 'false'
11
}
12
});
13
});
14
});