简体   繁体   English

根据数组元素生成复选框,然后根据选中的复选框填充另一个数组

[英]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.您可以为数组的每个元素创建一个包含inputlabeldiv元素。 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.

相关问题 基于复选框Ruby on Rails的动态数组 - Dynamic Array based on check boxes Ruby on Rails 根据复选框显示隐藏内容,如果选中一个复选框禁用另一个复选框 - Show hide content based on check boxes, if one check box checked disable another check boxes 获取选中的复选框并存储在数组javascript中 - get checked check boxes and store in array javascript 数组和复选框,我希望根据数组值选中/取消选中框,并在有人选中任何框并更新表单时更新数组 - array and checkboxes, I want boxes to checked/unchecked based on array values and also update array when someone check any box and update the form 根据数组值动态添加复选框 - dynamically add check boxes based upon array value javascript 根据选中的复选框数更改表单的文本字段 - Change text field of form based on number of check boxes checked 如何使用 Javascript 根据是否选中复选框显示警告框 - How to display alert boxes based on if a check box is checked or not using Javascript 根据使用CSS或JS选中的复选框数隐藏div - Hide divs based on number of check boxes checked with CSS or JS 使用jQuery根据用户输入(到另一个复选框)来选中复选框 - Using jQuery to check boxes based on user input (to another check box) 字符串数组,然后选择复选框 - String to array, then select check boxes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM