0
<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. AND I REQUEST YOU TO POST NO JQUERY SOLUTIONS. ONLY JAVASCRIPT.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Oscar Orcas
  • 117
  • 2
  • 4
  • 17

3 Answers3

2

You can pass the clicked element to your function:

<td><button type="button" class="mybutton" onclick="rowFunction(this)">Pay</button> </td>

and traverse the DOM:

function rowFunction(el) {
   var n = el.parentNode.parentNode.cells[0].textContent;
   // ...
}
Ram
  • 143,282
  • 16
  • 168
  • 197
0

You can use the HTML5 function document.querySelectorAll to get a list of your buttons, then add an event listener to them that will allow you to access their parent row, and get its first cell.

var buttons = document.querySelectorAll('#newtable tbody .mybutton');

function buttonClicked(e) {
    var button = this,
        cell = button.parentElement,
        row = cell.parentElement,
        firstCell = row.querySelector('td');
    alert(firstCell.innerHTML);
}

for (var i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener('click', buttonClicked);
}

Here is the fiddle I used to verify my code. Also, consider using CSS instead of JavaScript to style your rows' color and hover color. It will be cleaner and more maintainable in the long term.

cvializ
  • 616
  • 3
  • 11
0

Use Like

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

DEMO

cracker
  • 4,900
  • 3
  • 23
  • 41