简体   繁体   English

复选框侦听器未触发

[英]Checkbox listener not firing

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.我想根据复选框状态传递 row.id 和 boolean 。 But the problem is that it only works for the first checkbox: id and boolean state is passed.但问题是它只适用于第一个复选框:传递了 id 和布尔状态。

{% 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.我添加了 javascript 来监听复选框状态,并在检查后向 Flask 应用程序发送 POST 请求。 It works but it only fires when the first checkbox is checked, all other checkboxes generated by Jinja2 are ignored.它有效,但仅在选中第一个复选框时触发,忽略 Jinja2 生成的所有其他复选框。

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);
    }
  });
});
  1. You only get the first when you use querySelector当您使用 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你有 jQuery,所以使用它 - 它将一次性获取所有复选框,而无需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' } }); }); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM