简体   繁体   English

在javascript中获取选中的复选框(动态创建)值

[英]Get selected checkbox(dynamically created) value in javascript

I'm using the following code snippet for create a dynamic checkbox .我正在使用以下代码片段创建动态复选框

This code snippet is inside of the for loop .based on the for loop the check boxes will create.The main function is called in the html onload.代码片段位于for loop内。基于for loop复选框将创建。主函数在html onload 中调用。

This functionality is working fine.But if I choose the check box I need to get the value of the check box .I use the addEventListener its not working fine.此功能工作正常。但如果我选择复选框,我需要获取复选框的值。我使用addEventListener它不能正常工作。

var checkbox = document.createElement('input');
  checkbox.type = "checkbox";
  checkbox.name = "name";
  checkbox.value = teamIds;
  checkbox.id = i;
  checkbox.addEventListener("click",setTeamIdsinTextBox(teamNamesToShow),false);
  body.appendChild(checkbox);

Now I need, if I select the two checkboxes and I want to pass the both values to the setTeamIdsinTextBox function with comma separate string.现在我需要,如果我选择了两个复选框并且我想用逗号分隔的字符串setTeamIdsinTextBox function两个值传递给setTeamIdsinTextBox function

How can I do this?我怎样才能做到这一点? I need to achieve this with the javascript alone.我需要单独使用javascript来实现这一点。

so I need to frame the selected checkbox values like所以我需要将选定的复选框值框起来,例如

var teamNamesToShow ="firstselectedcheckboxvalue,secondselectedcheckboxvalue" var teamNamesToShow ="firstselectedcheckboxvalue,secondselectedcheckboxvalue"

Thanks in Advance.提前致谢。

The click listener needs to iterate over the checkboxes and collect the ids of those that are checked.点击侦听器需要遍历复选框并收集那些被选中的 ID。 You can use a selector to get just the checked ones, or filter the checked ones later which allows for a less complex selector.您可以使用选择器只获取选中的那些,或者稍后过滤选中的,这样可以使用不太复杂的选择器。

The following uses the more complex selector but simpler map callback:以下使用更复杂的选择器但更简单的地图回调:

 window.onload = function(){ var form = document.forms['form0']; for (var i=0; i<10; i++) { var checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.name = 'name' + i; checkbox.value = 'value' + i; checkbox.id = 'cb' + i; checkbox.addEventListener("click", setTeamIdsinTextBox, false); form.appendChild(checkbox); // add checkboxes to form, not body } } function setTeamIdsinTextBox() { var form = this.form; var cbs = Array.from(form.querySelectorAll('input[type="checkbox"]:checked')); var ids = cbs.map(function(cb) {return cb.id}); form.ta0.value = ids.join(', '); }
 <form id="form0"> <textarea id="ta0" name="ta0"></textarea> </form>

The body of the function could be:函数体可以是:

this.form.ta0.value =  Array.from(this.form.querySelectorAll('input[type="checkbox"]:checked')).map(function(cb) {return cb.id}).join(', ');

but I think splitting it over a couple of lines is more sensible.但我认为将它分成几行更明智。

Edit编辑

Array.from was introduced in ECMAScript 2015 so may not be available in all implementations in use. Array.from是在 ECMAScript 2015 中引入的,因此可能并非在所有使用的实现中都可用。 There's a polyfill at MDN that can be included to provide support where lacking. MDN上有一个polyfill ,可以包含它以在缺乏的地方提供支持。 Also, it can be replaced with Array.prototype.slice , which has ubiquitous support.此外,它可以替换为Array.prototype.slice ,它具有无处不在的支持。

Instead of:代替:

Array.from(form.querySelectorAll('input[type="checkbox"]:checked'));

use:用:

[].slice.call(form.querySelectorAll('input[type="checkbox"]:checked'));

however that may fail in IE 8 as (from memory) it doesn't allow calling built–in methods with a host object as this .但是,这可能会在 IE 8 中失败,因为(从内存中)它不允许使用主机对象调用内置方法作为this In that case, go directly to map and provide a polyfill for IE 8 :在这种情况下,直接去映射为 IE 8提供一个polyfill

[].map.call(form.querySelectorAll('input[type="checkbox"]:checked'), function(cb) {return cb.id});

That will work in IE 8 as the polyfill for map means that it's a native function, not built–in so using a NodeList as this is OK.这将在IE 8的工作作为填充工具在地图的手段,这是一个原生的功能,没有内置因此使用节点列表,因为是确定。 Versions of IE with map are OK with the host object thing.带有地图的 IE 版本可以处理主机对象。

In the for loop which you are iterating maintain an int variable which gives you the exact no.在您迭代的 for 循环中维护一个 int 变量,它为您提供确切的编号。 of checkboxes which you are going to create.And then using that again iterate through a for loop for that int variable and check for each checkbox whether it is checked or not.您将要创建的复选框。然后再次使用它遍历该 int 变量的 for 循环,并检查每个复选框是否被选中。

int countCheckBox=0;
var listOfCheckBoxVal='';

function setTeamIdsinTextBox(){

    for(int i =1; i<=countCheckBox;i++){

    if(document.getElementById(i).checked==true){

          listOfCheckBoxVal += document.getElementById(i).value+",";

    }

}

Now this listOfCheckBoxVal variable will have the list of values of checked checkboxes seperated by a comma.现在这个 listOfCheckBoxVal 变量将包含以逗号分隔的选中复选框的值列表。

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

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