Reputation: 13
I need to get specific td value of a dynamic table when button id='btn1' is clicked. The td value will be displayed in Display() which is a modal form.
here's my code for table row:
$query = "SELECT SID , FNAME , MNAME , LNAME , SCONTACT , MOTHER_FNAME , MOTHER_MNAME , MOTHER_LNAME , MCONTACT FROM student"; $result = mysqli_query($db, $query); $result_check = mysqli_num_rows($result); if($result_check > 0){ while ($row = mysqli_fetch_assoc($result))
{ echo "
<tr class='tr'>
<td class='nr'>" . $row["SID"] . "</td>"; echo "
<td>" . $row["FNAME"] ." ". $row["MNAME"] ." ". $row["LNAME"] . "</td>"; echo "
<td>" . $row["SCONTACT"] . "</td>"; echo "
<td>" . $row["MOTHER_FNAME"] ." ". $row["MOTHER_MNAME"] ." ". $row["MOTHER_LNAME"] . "</td>"; echo "
<td>" . $row["MCONTACT"] . "</td>"; echo "
<td>" . "<button id='btn1' onclick='Display()' class='inline'>Create Offense</button>"; } }
echo "</td></tr>";
Code for getting specific td value:
<script type="text/javascript">
$("#btn1").click(function() {
var num = $(this).parents("tr").find(".nr").text();
$(".resultas").text(num);
});
</script>
all I get is the first row td value. Any tips?
Upvotes: 0
Views: 1388
Reputation: 1126
You can try this:
$("#btn1").click(function() {
// change the number in bracket to get specific column value | td:eq(1)
var num = $(this).parents("tr").find("td:eq(1)").text();
alert(num);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tr>
<td>111</td>
<td>211</td>
<td>311</td>
<td><button id='btn1' class='inline'>Create Offense</button></td>
</tr>
</table>
Upvotes: 0
Reputation: 13506
You have set the same id for each element,so use class
instead of id
,change #btn1
to .inline
<script type="text/javascript">
$(".inline").click(function() {
var num = $(this).parents("tr").find(".nr").text();
$(".resultas").text(num);
});
</script>
Upvotes: 1