I wanted to be able to delete multiple records from a table just by selecting the records using checkbox
, same as Gmail, I select the emails that I want to delete or mark as read. Because when I need to delete some registry I still have to delete one at a time.
I'm very lay in JS
, until I was able to show in an alert the array with the ids that the user selected, but I do not know how to execute a sql statement to delete the marked records, the idea would be to delete it as soon as the user to click "OK" within the alert.
I've been searching the internet but I still have doubts, some examples used ajax.
Sample Code
<script type="text/javascript">
function coletaDados() {
var ids = document.getElementsByClassName('editar');
coletaIDs(ids);
}
function coletaIDs(dados) {
var array_dados = dados;
var newArray = [];
for (var x = 0; x <= array_dados.length; x++) {
if (typeof array_dados[x] == 'object') {
if (array_dados[x].checked) {
newArray.push(array_dados[x].id)
}
}
}
if (newArray.length <= 0) {
alert("Selecione um pelo menos 1 item!");
} else {
alert("Clique em OK para confirmar a exlusão do(s) registro(s) : [ " + newArray + " ]");
}
}
</script>
<?php
// Variáveis declaradas somente para ilustrar o exemplo
$id1 = "1";
$id2 = "2";
$id3 = "3";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tabela de Exemplo</title>
</head>
<body>
<table border="1" width="10%">
<tr>
<td>Registros</td>
</tr>
<tr>
<td><input type="checkbox" class="editar" id="<?php echo "$id1"; ?>"> A</td>
</tr>
<tr>
<td><input type="checkbox" class="editar" id="<?php echo "$id2"; ?>"> B</td>
</tr>
<tr>
<td><input type="checkbox" class="editar" id="<?php echo "$id3"; ?>"> C</td>
</tr>
<tr>
<td colspan="2"><button onclick="coletaDados()" class="btn btn-primary" style="width:100%">Excluir</button></td>
</tr>
</table>
</body>
</html>