[英]Know the checkbox selected if it created dynamically - Django
When I click a button I'm trying to know what checkbox
is selected.当我单击一个按钮时,我想知道选中了哪个checkbox
。 The problem is that the checkboxes are created dynamically with a for loop
in my template.问题是复选框是在我的模板中使用for loop
动态创建的。
html网页格式
<form action="#" method="post" target="#">
{% for node in Last_val_nodes %}
<input type="checkbox" class="nodeRuta" name="{{node.0}}">{{node.0}}<br>
{% endfor %}
</form>
JS JS
$('#filtrar_btn_map').click(function(){
if( $(".nodeRuta").is(':checked') ) {
var node = $(".nodeRuta").attr("name");
alert(node);
}
});
Last_val_nodes
is a list like [['node1',1,2],['node2',4,5],['node3',7,8]]
and with my code the alert
is always showing node1
, whatever checkbox is selected. Last_val_nodes
是一个类似于[['node1',1,2],['node2',4,5],['node3',7,8]]
列表,使用我的代码, alert
始终显示node1
,无论复选框是什么选择。
I tried with var node = $(this).attr("name");
我尝试使用var node = $(this).attr("name");
but it's not working too.但它也不起作用。 Can somebody help me, please?有人可以帮我吗?
Thank you very much.非常感谢你。
You need to use the :checked
selector and length
to find if any of the checkboxes have been checked.您需要使用:checked
选择器和length
来查找是否已选中任何复选框。
That being said, depending on your needs, it would make more sense to either loop over all the checked items directly:话虽如此,根据您的需要,直接遍历所有选中的项目会更有意义:
$('#filtrar_btn_map').click(function() {
$(".nodeRuta:checked").each(function() {
var node = this.name;
console.log(node);
}
});
Or alternatively you can use map()
to build an array of the selected values:或者您可以使用map()
来构建所选值的数组:
$('#filtrar_btn_map').click(function() {
var values = $(".nodeRuta:checked").map(function() {
return this.name;
}).get();
console.log(values);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.