Checkbox listener not firing

Tags: , ,



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.

{% for row in list %}
   ....
    <label>
      Off
      <input name="active{{ row.id }}" id="active{{ row.id }}" type="checkbox" list_id="{{ row.id }}">
      <span class="lever"></span>
      On
    </label>
   ....
{% endfor %}

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.

document.addEventListener('DOMContentLoaded', function () {
  var checkbox = document.querySelector('.input[type="checkbox"]');
  checkbox.addEventListener('change', function () {
  var list_id = $(this).attr('list_id');
  
    if (checkbox.checked) {
        req = $.ajax({
          url : '/dashboard',
          type : 'POST',
          data : { id: list_id, active : 'true' }
        });

      console.log(list_id);
    } else {
          req = $.ajax({
          url : '/dashboard',
          type : 'POST',
          data : { id : list_id, active: 'false' }
        });
      console.log(list_id);
    }
  });
});

Answer

  1. You only get the first when you use querySelector
  2. you have a dot in front of the input that should not be there
  3. You have jQuery, so use it – it will take all checkboxes in one go without the need for querySelectorAll

$(function() {
  $('input[type="checkbox"]').on('change', function() {
    var list_id = $(this).attr('list_id');
    console.log(list_id);
    req = $.ajax({
      url: '/dashboard',
      type: 'POST',
      data: {
        id: list_id,
        active: this.checked ? 'true' : 'false'
      }
    });
  });
});


Source: stackoverflow