JavaScript点击表格按钮如何获取对应行的reqproid数据?
Solution
Step 1: Fix the HTML (Thymeleaf)
Remove duplicate id attributes from elements in the loop (ids must be unique across the page):
<tr th:each="pendingStock,iStat:${listPenddingByID}" name="line_items"> <td th:text="${pendingStock.reqproid}" hidden name="reqproid" class="reqproid"></td> <td> <a style="padding: 10px;" class="detailsButton"><i class="ti-pencilalt">View</i></a> </td> </tr>
Step 2: Correct the JavaScript
Instead of selecting all .reqproid elements, traverse the DOM to find the one in the same row as the clicked button:
$('.table .detailsButton').on('click', function(event){ // Get the parent row of the clicked button, then find the reqproid td inside it let productid = $(this).closest('tr').find('.reqproid').text().trim(); alert(productid); });
Why the original code failed:
document.querySelectorAll('.reqproid')returns a NodeList of all matching elements, not a single element. Accessing.valueon this list is invalid (and even if it worked, it would grab the first element's value, not the clicked row's).- The
tdelement usesth:textto set its content, so you need to retrieve its text content (.text()) instead ofvalue(which is for input elements). - Duplicate
idattributes break HTML validity and can cause unexpected behavior with selectors.
内容的提问来源于stack exchange,提问作者Jav JakSmoke
相关产品推荐
相关产品推荐

