[英]Generate check boxes based on array elements then populate another array based on checked check boxes
Let's say we have an empty array that we want to populate it based on checked checkboxes :假设我们有一个空数组,我们想根据选中的复选框填充它:
let selected = [];
And another array of some person names:还有一些人名的另一个数组:
let names = ['Joe', 'Mike', 'Sara', 'Jack'];
I want to generate checkboxes for each of the name's
elements first, then I want to add each checked element to the selected
array.我想首先为name's
每个元素生成复选框,然后我想将每个选中的元素添加到selected
数组中。
I can do this with drop-downs (code below) but I have no idea how this could be done with checkboxes:我可以用下拉菜单(下面的代码)来做到这一点,但我不知道如何用复选框来做到这一点:
let dropDown = document.getElementById('names'); let selected = []; let names = ['Joe', 'Mike', 'Sara', 'Jack']; // Loop through each of the voices. names.forEach(function(e, i) { // Create a new option element. var option = document.createElement('option'); // Set the options value and text. option.value = names[i]; option.innerHTML = names[i]; // Add the option to the voice selector. dropDown.appendChild(option); }); // 3 seconds to select the item setTimeout(function() { if (dropDown.value) { selected.push(dropDown.value) } console.log(selected) }, 3000)
<div class="option"> <label for="voice">US Pronunciation:</label> <select name="voice" id="names"></select> </div>
You'll have to add an onClick event handler for the checkboxes and add them to the select that way.. Something like this should get you started:您必须为复选框添加一个 onClick 事件处理程序,并以这种方式将它们添加到选择中..这样的事情应该让您开始:
let dropDown = document.getElementById('names'); let container = document.getElementById('container'); let selected = []; let names = ['Joe', 'Mike', 'Sara', 'Jack']; // Loop through each of the voices. names.forEach(function(e, i) { let html = ` <input onClick="handleCheck('container', 'names')" type="checkbox" name="checkbox" id="${i}_${e}" value="${e}"> <label for="${i}_${e}">${e}</label> `; container.innerHTML += html; }); function handleCheck(containerElementId, inputElementId) { let containerElement = document.getElementById(containerElementId); let select = document.getElementById(inputElementId); select.innerHTML = ""; selected = []; containerElement.querySelectorAll('input[type="checkbox"]').forEach(el => { if(el.checked) { select.innerHTML += `<option value="${el.value}">${el.value}</option>`; selected.push(el.value); } }) console.log("selected", selected); }
<div class="option" id="container"> <label for="voice">US Pronunciation:</label> <select name="voice" id="names"></select> </div>
You can create a div
element containing an input
and a label
for each element of the array.您可以为数组的每个元素创建一个包含input
和label
的div
元素。 Each one of these elements needs to be appended to an existing parent element option
.这些元素中的每一个都需要附加到现有的父元素option
。 You can achieve this by writing down the actual HTML inside back-quotes.您可以通过写下反引号内的实际 HTML 来实现这一点。 Then create an empty element with document.createElement
.然后使用document.createElement
创建一个空元素。 Using the innerHTML
property you can fill this element with the HTML you wrote.使用innerHTML
属性,您可以用您编写的HTML 填充此元素。 Finally append it like you did using appendChild
:最后像使用appendChild
一样附加它:
const html = `
<div>
<input type="checkbox" id="${name}" name="${name}">
<label for="${name}">${name}</label>
</div>
`.trim();
const wrapper = document.createElement('div');
wrapper.innerHTML = html;
const element = option.appendChild(wrapper.firstChild);
Instead of using forEach
to loop through your array, I would use map
which allows us to create an array of input
elements on the go.我不会使用forEach
循环遍历数组,而是使用map
,它允许我们随时随地创建input
元素数组。 It's the exact same as using a forEach
... the only difference is you need to return an element in your callback function:它与使用forEach
完全相同……唯一的区别是您需要在回调函数中返回一个元素:
const checkboxes = names.map(function(name) {
const html = `
<div>
<input type="checkbox" id="${name}" name="${name}">
<label for="${name}">${name}</label>
</div>
`.trim();
const wrapper = document.createElement('div');
wrapper.innerHTML = html;
const element = option.appendChild(wrapper.firstChild);
return element.querySelector('input');
});
So now we have an array called checkboxes
which holds four input
elements corresponding to our four names contained in the initial names
array.所以现在我们有一个名为checkboxes
的数组,它包含四个input
元素,对应于包含在初始names
数组中的四个名称。
Whenever you need to know the checkboxes that are checked you can filter them out and get the names of the remaining ones.每当您需要知道选中的复选框时,您可以将它们过滤掉并获取其余复选框的名称。 We'll do this using filter
and another map
:我们将使用filter
和另一个map
来做到这一点:
checkboxes.filter(checkbox => checkbox.checked)
.map(checkbox => checkbox.name);
Here's the full code:这是完整的代码:
const option = document.querySelector('.option'); const names = ['Joe', 'Mike', 'Sara', 'Jack']; const checkboxes = names.map(function(name) { const html = ` <div> <input type="checkbox" id="${name}" name="${name}"> <label for="${name}">${name}</label> </div> `.trim(); const wrapper = document.createElement('div'); wrapper.innerHTML = html; const element = option.appendChild(wrapper.firstChild); return element.querySelector('input'); }); setTimeout(function() { const selected = checkboxes.filter(checkbox => checkbox.checked); console.log(selected.map(checkbox => checkbox.name)); }, 3000)
<div class="option"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.