简体   繁体   中英

JavaScript - Get data of first cell of selected table row

<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 ie 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.

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 ie td and we select the parent of td ie 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()

$(".mybutton").click(function(){
    alert($(this).parent().siblings().eq(0).text());
});

通常我使用DataTables js作为解决方案,可以在以下位置进行检查: https : //datatables.net/reference/api/row().data()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM