Skip to content

Instantly share code, notes, and snippets.

@porfidev
Created October 4, 2019 16:46
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save porfidev/667af196f48b2dbac62b7201fb4a1d7d to your computer and use it in GitHub Desktop.
Como sumar los radio buttons de un formulario con Javascript en 2019
<html>
<head>
<title>CAFETERIA</title>
<meta charset="utf-8" />
<style>
body {
background-color: #e1e637;
}
h1 {
color: #ff090e;
}
legend {
margin-top: 20px;
margin-bottom: 10px;
}
</style>
</head>
<body>
<h1>CAFETERIA</h1>
<form>
<legend>SELECCIONE EL PLATO PRINCIPAL</legend>
<input type="radio" id="n1" name="principal" value="12" /> Caldo de pollo
Q12.00 <br /><br />
<input type="radio" id="n2" name="principal" value="20" /> pescado frito
Q20.00<br /><br />
<input type="radio" id="n3" name="principal" value="25" /> revolcado
Q25.00<br /><br />
<legend>SELECCIONE SU BEBIDA</legend>
<input type="radio" id="n4" name="bebida" value="7" /> CocaCola Q7.OO<br /><br />
<input type="radio" id="n5" name="bebida" value="4" /> Jamaica Q4.00<br /><br />
<input type="radio" id="n6" name="bebida" value="5" /> Sprite Q5.00<br /><br />
<legend>SELECCIONE SU POSTRE</legend>
<input type="radio" id="n7" name="postre" value="7" /> Pastel de fresa
Q7.oo<br /><br />
<input type="radio" id="n8" name="postre" value="5" /> Helado de Chocolate
Q5<br /><br />
<input type="radio" id="n9" name="postre" value="9" /> Coctel de frutas
Q9.00<br /><br />
<button>Obtener TOTAL</button>
</form>
<script>
// buscar el <form> y guardarlo en una variable
const form = document.querySelector('form');
// decir que en el evento enviar se sume el total
form.addEventListener('submit', obtenerTotal);
function obtenerTotal(event) {
// evitar enviar el formulario que ocasiona que se refresque la pagina
event.preventDefault();
// obtener todos los input radio
const formData = new FormData(event.target);
// convertir los valores a String, o colocar un 0 si no elegieron algo
const principal = parseInt(formData.get('principal') || '0', 10);
const bebida = parseInt(formData.get('bebida') || '0', 10);
const postre = parseInt(formData.get('postre') || '0', 10);
const result = principal + bebida + postre;
alert("la suma es:" + result);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment