codice:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Somma Valori Checkbox</title>
</head>
<body>
<h2>Lista Articoli</h2>
<table>
<tr>
<th>Nome</th>
<th>Prezzo (€)</th>
<th>Seleziona</th>
</tr>
<tr>
<td>Tavolo</td>
<td>35</td>
<td><input type="checkbox" name="articoli[]" value="35" onchange="calcolaTotale(this)"></td>
</tr>
<tr>
<td>Sedia</td>
<td>24</td>
<td><input type="checkbox" name="articoli[]" value="24" onchange="calcolaTotale(this)"></td>
</tr>
<tr>
<td>Piatto</td>
<td>12</td>
<td><input type="checkbox" name="articoli[]" value="12" onchange="calcolaTotale(this)"></td>
</tr>
</table>
<p>Totale: € <input type="text" id="totale" value="0" readonly></p>
<script>
// Funzione per calcolare il totale
function calcolaTotale(checkbox) {
let totale = parseFloat(document.getElementById('totale').value); // Recupera il totale corrente
let valore = parseFloat(checkbox.value); // Valore del checkbox selezionato
// Aggiunge o sottrae il valore dal totale in base al checkbox selezionato o deselezionato
if (checkbox.checked) {
totale += valore;
} else {
totale -= valore;
}
// Aggiorna il campo di testo con il nuovo totale
document.getElementById('totale').value = totale.toFixed(2);
}
</script>
</body>
</html>