Search code examples
javascriptspringthymeleaf

How to get data when I click on array in javascrpit


$('.table .detailsButton').on('click',function(event){
        
        let productid = document.querySelectorAll('.reqproid').value;
        
        alert(productid);
        
    });

This is my Data on spring

<tr th:each="pendingStock,iStat:${listPenddingByID}" name="line_items">
    <td th:text="${pendingStock.reqproid}" hidden name="reqproid" id="reqproid"class="reqproid"></td>
    <td>
        <a style="padding: 10px;" id="detailsButton" class="detailsButton"><i class="ti- pencilalt">View</i></a>
    </td>
</tr>

Example that When I Click oh view after that is show alert reqproid


Solution

  • Since you want to associate your View button with a specific value that is on the same row with the button, you shouldn't use document.querySelectorAll('.reqproid') that will return you all elements of this class on the page.

    Here is what you can do instead:

    $('.table .detailsButton').on('click', function(event) {
      const row = event.target.parentNode.parentNode.parentNode;
      const productid = row.querySelector('.reqproid').innerText;
      alert(productid);
    });
    <html>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <body>
      <table class="table">
        <tr th:each="pendingStock,iStat:${listPenddingByID}" name="line_items">
          <td th:text="${pendingStock.reqproid}" hidden name="reqproid" id="reqproid" class="reqproid">1234</td>
          <td>
            <a style="padding: 10px;" id="detailsButton" class="detailsButton"><i class="ti- pencilalt">View</i></a>
          </td>
        </tr>
      </table>
    </body>
    
    </html>

    Please let me know if this helps.