I am very new to JS/PHP/web dev in general so apologies if this is a very basic question, but I'm trying to make each <td>
element in a table clickable, and also get the text of that <td>
on click.
Right now I have a SQL query that runs when a date input is selected, and returns a column of basketball game IDs that occurred on the date that is selected.
What I'm having trouble with is making each individual <td>
clickable when the query populates the table. Currently my code works, but only the first <td>
is clickable.
Here is the PHP code I have that gives me the Game IDs for the date selected (apologies for bad formatting)
<table>
<tbody>
<tr>
<?php
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
?>
<td id='matchuptable' onclick="game_ids()">
<?php echo $row['GAME_ID']?>
</td>
<?php
}
?>
</tr>
</tbody>
</table>
Here is my JS function that is called when the <td>
is clicked:
<script type=text/javascript src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
function game_ids()
{
var gid = document.getElementById("matchuptable").innerText;
alert(gid)
$.post('gamelogs.php',{game_ids_name:gid},function(data){$('#gamelogs_here').html(data)})};
</script>
I am positive there is a much much cleaner way to do this, and any tips/advice on formatting would be much appreciated. Thanks
The id attribute should be unique, I suggest you to add a counter and append it to your base id. You can also add a parameter to your game_ids() function and pass this (that represent the current element clicked), avoiding a DOM lookup:
<tr>
<?php
$rowCount = 0;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)):
$rowCount++;
?>
<td id="matchuptable-<?=$rowCount?>" onclick="game_ids(this)">
<?php echo $row['GAME_ID']?>
</td>
<?php
endwhile;
?>
</tr>
I've used the while(): - endWhile; syntax for better readability
In the JS code you get the clicked element as a parameter:
function game_ids(el)
{
alert(el.innerText);
$.post('gamelogs.php',{game_ids_name:gid},function(data){$('#gamelogs_here').html(data)});
}