Search code examples
jqueryjspjstl

Pass row id in a table displayed using jstl to jquery on click of row


I am displaying list of data as table using jstl foreach loop.On click of a row,the respective ID value in the row needs to be sent to jquery onclick() function. Table-

  <table border="1" width="90%" class="table-hover" id="warehouseValue">

    <tr>
        <th>Warehouse Id</th>
        <th>Warehouse Location</th>
        <th>Warehouse City</th>
        <th>Zone</th>
    </tr>

     <c:forEach items="${sessionScope.listWarehouse}" var="description">
         <tr>        
            <td>
               <input type="hidden" id="idValue" value="${description.getWarehouseId()}" />
               ${description.getWarehouseId()}
            </td>
            <td>${description.getWarehouseLocation()}</td>
            <td>${description.getWarehouseCity()}</td>
            <td>${description.getWarehouseDescription().getZone()}</td>
        </tr>
     </c:forEach> 
</table>

Jquery onclick() function-

$(document).ready(function() {
   $("#warehouseValue").click(function() {
      var rowId = document.getElementById("idValue").value;
      alert("new "+rowId);
   });
});

Here on click of any row only the first row's id-${description.getWarehouseId()} is getting displayed. How do i make the respective Id value of each row be sent to onclick() function


Solution

  • You can get like this. td has a child input element.

    $("#warehouseValue").on('click','td',function(event) {
            // td has a child input 
            var value1 = $(event.target.children[0]).val();
            var value2 = $(event.target).children("input").val();
            console.log(value1+" "+value2);
    });