Reputation: 1291
I have a HTML table generated from PHP (from the results of SQL query):
echo "<table border=\"5\"><tr><th>Codice</th><th>Titolo</th><th>Anno Creazione</th><th>Materiale</th><th>Altezza</th><th>Peso</th><th>Museo</th></tr>";
while($row = mysqli_fetch_assoc($results)) {
echo "<tr><td>".$row["Codice"]."</td><td>".$row["Titolo"]."</td><td>".$row["Anno_creazione"]."</td><td>".$row["Materiale"]."</td><td>".$row["Altezza"]."</td><td>".$row["Peso"]."</td><td>".$row["Museo"]."</td><td><button id=\"modifica\" type=\"button\">Modifica</button></td><td><button id=\"cancella\" type=\"button\">Cancella</button></td></tr>";
}
echo "</table>";
Then, I have this JQuery:
$("#cancella").click(function(){
if(confirm("Vuoi davvero eliminare questi dati?")){
var codice = <?php echo json_encode($cod); ?>;
var tipo = <?php echo json_encode($tipo_opera); ?>;
window.location.href = "delete.php?codice="+codice+"&tipo="+tipo;
}
});
This click function works only for the "delete" button at the first row. Why?
Upvotes: 0
Views: 1611
Reputation: 562
The id should be unique, if that is repeating in your DOM structure then you will face the problem. Use class cancella something and then define some data attribute to identify specific element if you want to.
So your code will be...
In Html
echo "<tr><td>".$row["Codice"]."</td><td>".$row["Titolo"]."</td><td>".$row["Anno_creazione"]."</td><td>".$row["Materiale"]."</td><td>".$row["Altezza"]."</td><td>".$row["Peso"]."</td><td>".$row["Museo"]."</td><td><button id=\"modifica\" type=\"button\">Modifica</button></td><td><button data-myid=".$row['id']." class='cancella' type=\"button\">Cancella</button></td></tr>";
In JS
$(".cancella").click(function(){
if(confirm("Vuoi davvero eliminare questi dati?")){
var particular_element = $(this).attr('data-myid');
}
});
Also if you are dynamically adding "more" elements then you should use $(document).on('click', '.cancella', function(){});
instead of $(".cancella").click()
, hope it helps.
Upvotes: 0
Reputation: 3342
id is unique and therefore can only be assigned to one element
.
use a class
.
<button class=\"cancella\" type=\"button\">Cancella</button>
$(".cancella").click(function(){
// Do Something.
});
Alternative:
<button type=\"button\" onclick=\"cancella()\">Cancella</button>
function cancella(){}
Upvotes: 1
Reputation:
<button id=\"cancella\" type=\"button\">Cancella</button>
needs to be a class not an id
Upvotes: 0