How can I have the button raise an alert only showing the persons first name and last name from the same row as the button?
I've pasted my current code from jsfiddle below, but the button returns an empty string.
Am I interpreting the javascript incorrectly?
- Get the closest table row to the button, so the same table row as the button and save it in the row variable.
- search for every table data container within the same table row to the button.
- create a variable "person"
- within the current row find html within a label and a FirstName/LastName class.
- Show a message containing a string conversion of the now populated "person" variable.
HTML
$("button").on("click", function() {
var row = $(this).closest("tr");
$("td", row).each(function() {
var person = {};
person.FirstName = row.find(".label").find(".FirstName").html();
person.LastName = row.find(".label").find(".LastName").html();
alert(JSON.stringify(person));
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><span class="label FirstName">John</span></td>
<td><span class="label LastName">Doe</span></td>
<td><button class="button">Button 1</button></td>
</tr>
<tr>
<td><span class="label FirstName">Richard</span></td>
<td><span class="label LastName">Roe</span></td>
<td><button class="button">Button 2</button></td>
</tr>
</table>
tdelements? You're not doing anything with them. There's only one person in each row, but you're alerting it 3 times because there are 3 cells.