如何使用javascript通过单击复选框向数组添加id?

如何使用javascript通过单击复选框向数组添加id?,javascript,jquery,html,thymeleaf,Javascript,Jquery,Html,Thymeleaf,我有一个带有一些值的表,最后一个输入是一个复选框。 我只需要在选中时将输入的id保存到数组中 这是我的部分表格: <table id="produtcTable" class="table"> <thead class="thead-dark"> <tr> <th scope="col">Producto</th> <th scope="col">Precio

我有一个带有一些值的表,最后一个输入是一个复选框。 我只需要在选中时将输入的id保存到数组中

这是我的部分表格:

<table id="produtcTable" class="table">
   <thead class="thead-dark">
       <tr>
           <th scope="col">Producto</th>
           <th scope="col">Precio de lista</th>
           <th scope="col">Agregar</th>
       </tr>
   </thead>
   <tbody>
       <tr th:each="stock : ${stockList}">
           <td th:text="${stock.productName}"></td>
           <td th:text="${stock.price}"></td>
           <td class="text-center">
               <input class="form-check-input" type="checkbox" th:attr="id=${stock.stockCode}" onclick="myFunction(this)" aria-label="...">

产品
利斯塔精品酒店
阿格雷戈
这是我的javascript,无法工作:

<script >
   function myFunction(product) {
       var arr= [];
       $('input[id='+ product.id +']:checked').each(function () {
             arr.push(product.id);
             });
        alert(arr.toString());
        };
</script>

功能myFunction(产品){
var-arr=[];
$('input[id='+product.id+']:选中')。每个(函数(){
arr.push(产品id);
});
警报(arr.toString());
};

我做错了什么?

在代码片段中,我看不到您的id属性复选框。但是有一些代码我无法识别(在文章中没有提到)设置id。请确保当前DOM(浏览器开发工具:inspector)中有id。根据您的代码片段,您可以尝试以下操作:

<input type="checkbox" id="cb1" onclick="myFunction(this)"/>
<input type="checkbox" id="cb2" onclick="myFunction(this)"/>

我认为要使
onclick
正常工作,您需要将它放在inputh的包装器中。您是否尝试过console.log(产品)?或console.log($('input[id='+product.id+']:checked'))?我想你会发现你的一些问题…我会试试it@devlincarnate我确认显示了id,但在Alerts中看不到该数组。您是否尝试迭代该数组以查看其内容?(或者使用console.log()来检查它)。工作起来就像一个符咒!太快了。非常感谢。
var arr= [];
function myFunction(inputCB) {
  arr.push(inputCB.id);
  alert(arr);
}