【问题标题】:How do I pass the values of checked boxes to an array using javascript (not jQuery)?如何使用 javascript(不是 jQuery)将复选框的值传递给数组?
【发布时间】:2020-10-11 17:28:01
【问题描述】:

这里是新手编码器。我已经找了几个小时了,但一直找不到我要找的东西(但很接近!)。我正在使用 javascript 和 HTML 尝试将检查项的值放入一个数组中,然后显示该数组(此时)以检查我是否已将值传递给该数组。

我已经成功测试了我的 .js 和 .html 文件是否已链接,我可以手动在数组中定义一个元素并且该元素将显示,但我似乎无法弄清楚如何获取“值”一个复选框传递到数组中。目前正在尝试一个 for 循环(在另一篇文章中找到)没有运气。这是几行 HTML:

var grocItems = [];

var checkboxes = document.querySelectorAll("input[type=checkbox]:checked");

function sendProduce() {
  for (var i = 0; i < checkboxes.length; i++)
    grocItems.push(checkboxes[i].value);

  alert(grocItems);
  
}
<div class=columns id=produceOne>

  <input type="checkbox" name="produceitem" id="apples" value=" apples ">
  <label for="apples ">Apples</label><br>
  <input type="checkbox" name="produceitem " id="avocados " value="avocados ">
  <label for="avocados ">Avocados</label><br>

</div>

感谢您的帮助!

【问题讨论】:

    标签: javascript html arrays checkbox


    【解决方案1】:

    在函数内移动 checkboxes 变量:

    var grocItems = [];
    
    function sendProduce() {
      grocItems = [];
      var checkboxes = document.querySelectorAll("input[type='checkbox']:checked");
      for (var i = 0; i < checkboxes.length; i++) {
        grocItems.push(checkboxes[i].value);
      }
      
      console.log(grocItems);
    }
    

    【讨论】:

    • 我只是移动了它,并没有改变任何其他东西,它正在用选定的项目提醒数组......谢谢!
    • 您应该知道,如果您调用此代码两次,数组中的旧值不会被删除,而是会添加新值。
    • ty Poul,我修好了。
    【解决方案2】:

    该表达式checkboxes = ...pageload 上进行评估,因此您需要将其移动到一个函数中,然后在准备好时读取选中的复选框。页面加载,脚本查找任何带有input:checked 选择器的复选框,但尚未选中任何复选框,因此它存储了一个稍后查找且不会更改的空结果。

    您可以将您的逻辑绑定到输入的click 事件,以便您的函数在选中一个框时运行。

    function sendProduce() {
      let checked = document.querySelectorAll('input[type=checkbox]:checked'),
          grocItems = Array.from(checked).map(
            checkbox => checkbox.value.trim()
          );
    
      console.log(grocItems);
    }
    
    let checkboxes = document.querySelectorAll('input[type=checkbox');
    Array.from(checkboxes).forEach(
      checkbox => checkbox.addEventListener('click', sendProduce)
    );
    <div class=columns id=produceOne>
    
      <input type="checkbox" name="produceitem" id="apples" value=" apples ">
      <label for="apples ">Apples</label><br>
      <input type="checkbox" name="produceitem " id="avocados " value="avocados ">
      <label for="avocados ">Avocados</label><br>
    
    </div>

    【讨论】:

      【解决方案3】:

      一个简单的方法是将它连接到一个 onchange 事件,以便在单击复选框时,您可以看到您单击的内容,然后(立即触发)当前在数组中的内容。

      <!doctype html>
      <html lang="en">
        <head>
          <title>Title</title>
          <!-- Required meta tags -->
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
          <!-- Bootstrap CSS -->
          <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        </head>
        <body>
      
          <div class=columns id=produceOne>
              <input onChange="sendProduce(this)" type="checkbox" name="produceitem" id="apples" value="apples"><label for="apples">Apples</label><br>
              <input onChange="sendProduce(this)" type="checkbox" name="produceitem" id="avocados" value="avocados"><label for="avocados">Avocados</label><br>
            </div>
          <!-- Optional JavaScript -->
          
          <!-- jQuery first, then Popper.js, then Bootstrap JS -->
          <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
          <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
          <script>
              var grocItems = [];
              var checkboxes = document.querySelectorAll("input[type=checkbox]:checked");
              function sendProduce(item) {
                  alert("Checkbox clicked: " + item.value)
                  grocItems.push(item.value); 
                  alert("Array: " + grocItems);
                }
          </script>
          </body>
      </html>

      【讨论】:

        猜你喜欢
        • 2015-06-07
        • 1970-01-01
        • 1970-01-01
        • 2011-10-19
        • 1970-01-01
        • 1970-01-01
        • 2014-12-29
        • 2021-02-05
        • 1970-01-01
        相关资源
        最近更新 更多