1
<table border="1" cellpadding="5" id="newtable">
                    <tr>
                        <th>Room No</th>
                        <th>AC</th>
                        <th>Deluxe</th>
                        <th>Tariff</th>
                    </tr>
                    <c:forEach var="room" items="${myrooms}">
                        <tr bgcolor="#4B476F" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#4B476F';">

                            <td class="nr"><c:out value="${room.roomno}" /></td>
                            <td><c:out value="${room.ac}" /></td>
                            <td><c:out value="${room.deluxe}" /></td>
                            <td>&#8377;<c:out value="${room.price}" /></td>
                            <td><button type="button" class="mybutton" onclick="rowFunction()">Pay</button> </td>
                        </tr>
                    </c:forEach>
                </table>

On clicking the button corresponding to every row, I want my script to return the Room number i.e. the first cell data of the row. I have tried a lot of things after referring various articles on the Internet. Nothing seems to work. Please help.

Oscar Orcas
  • 117
  • 1
  • 4
  • 15

3 Answers3

1

You can use something like

Demo

$(window).on('click', '.mybutton' ,function() {
    alert($(this).parent().parent().find('.nr').text());
    //Or you can use, which is even better
    //alert($(this).parent().siblings('.nr').text());
});

Here, the selector is pretty simple, we are first binding click event on the button, and onclick we select the button element parent i.e td and we select the parent of td i.e tr and later we find an element with a class of .nr

You can also write td.nr instead of just .nr to be more specific.

Your rows are being dynamically added, in order for your click listener to work you will have to delegate the events

Credits to @Patsy Issa for suggesting .siblings()

Community
  • 1
  • 1
Mr. Alien
  • 140,764
  • 31
  • 277
  • 265
0
$(".mybutton").click(function(){
    alert($(this).parent().siblings().eq(0).text());
});
Eternal1
  • 4,917
  • 1
  • 27
  • 43
0

usually im using DataTables js for solution, you can check at: https://datatables.net/reference/api/row().data()

Ilham
  • 21
  • 9