Assign variable php as attribute id of a div tag

0

I want to generate a alert by giving click to each of the numbers in the table that is generated with the for . The alert works, but I want it to be the same number in the box that I click on. In this case the error is that the first value continues to be output, that is:

<?php

$indice=1;
$filas = 100;

echo "<table border= 1; id='table'>";

echo "<th> Numeros </th>";

for($i = 1; $i <= $filas; $i++){

    echo "<tr>";
    echo "<td>";
    echo "<div id='numero' onclick='alertNumero()'>";
    echo $indice++;
    echo "</div>";
    echo "</td>";
    echo "</tr>";
}

?>
<script>

function alertNumero(){
    var x = document.getElementById("numero").innerHTML;
    alert(x);
}

</script>
    
asked by noraprogramadora 21.05.2018 в 22:20
source

1 answer

1

The problem is that all HTML tags you assign the ID 'number', so the function always takes the first. I recommend that you assign the $ i as Index

<?php    
    echo "<table border= 1; id='table'>";    
    echo "<th> Numeros </th>";    
    for($i = 1; $i <= $filas; $i++){    
        echo "<tr>";
        echo "<td>";
        echo "<div id='.$i.' onclick='alertNumero('.$i.')'>";
        echo $i;
        echo "</div>";
        echo "</td>";
        echo "</tr>";
    }    
?>
<script>
    function alertNumero(e){
        alert(e);
    }
</script>

La otra opción es capturar el evento Click, y desde esa obtener el objeto que disparo el evento "alertNumero(event)", así:

<?php    
    echo "<table border= 1; id='table'>";    
    echo "<th> Numeros </th>";    
    for($i = 1; $i <= $filas; $i++){    
        echo "<tr>";
        echo "<td>";
        echo "<div id='.$i.' onclick='alertNumero(event)'>";
        echo $i;
        echo "</div>";
        echo "</td>";
        echo "</tr>";
    }    
?>
<script>
    function alertNumero(event){
        alert(event.target.innerHTML());
    }
</script>
    
answered by 21.05.2018 / 22:26
source