Mikkel Bertelsen Mikkel Bertelsen - 6 months ago 12
Javascript Question

Table with FOREACH joinable content

My problem is that I don't know how to make a function that has the same id as my

$loop['id']
that I created with
foreach
loop.

foreach ($getongoing as $loop) {
echo "<tr>";
echo "<td>" . $loop['id'] . "</td>";
echo "<td>" . $loop['player1'] . "</td>";
echo "<td>" . "$" . $loop['bet1'] . "</td>";
echo "<td>" . '<html><img src="images/'.$loop['site1'].'.png" width="25" height="25"/></html>' . "</td>";


Within my loops I create a button, which has the
$loop['id']


echo '<td><button type="button" class="btn btn-link" onClick="'.$loop['id'].'()" id="test">Join game</button></td></tr>';


I would like to make a function/script which comes up with a altert box, asking if I really want to join
$loop['id']
with the bet of
$loop['bet1']


This is the script that I want to appear when clicking on the specfic join button

<script>
function myFunction() {
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = x;
}
</script>

Answer

Instead of creating and calling function using the value of $loop['id'], you can simply pass the value as parameter, see example below:

echo '<td><button type="button" class="btn btn-link" onClick="myFunction(' . $loop['id'] . ');" id="test">Join game</button></td></tr>';

<script>
function myFunction(id) {
    console.log(id);
    var x;
    if (confirm("Press a button!") == true) {
            x = "You pressed OK!";
    } else {
            x = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = x;
}
</script>
Comments