Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - 知道复选框是动态创建的-Django(Know the checkbox selected if it created dynamically - Django)

When I click a button I'm trying to know what checkbox is selected.

(当我单击一个按钮时,我试图知道checkbox哪个checkbox 。)

The problem is that the checkboxes are created dynamically with a for loop in my template.

(问题是复选框是在模板中动态创建的,带有for loop 。)

html

(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.

(非常感谢你。)

  ask by NEA translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...