我有一个带有一些值的表,最后输入是一个复选框。
我仅在选中时才需要将输入的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>
我究竟做错了什么?
最佳答案
我在摘要中的复选框上看不到id属性。但是有一些代码我无法识别(后文未提及)设置ID。请确保您当前的DOM中有一个ID(浏览器开发工具:检查器)。根据您的摘要,您可以尝试以下方法:
<input type="checkbox" id="cb1" onclick="myFunction(this)"/>
<input type="checkbox" id="cb2" onclick="myFunction(this)"/>
以下JS代码将更新单击的复选框ID的全局数组:
var arr= [];
function myFunction(inputCB) {
arr.push(inputCB.id);
alert(arr);
}