I want to add the values of a input
with name monto_pagar
and the value of multiple checkboxes
(the generated checkbox number goes from 1 to N) and display them in input
with name total_id
.
My problem occurs when the number of checkbox
is greater than 1, only adds the last checkbox
generated. I guess the problem is in the way I get the value of the changing ID.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
$precio=100000;
$i = 1;
$cuotas_pendientes=4; //Si el valor es a 1 me funciona correctamente, pero cuando es mayor de 1 es donde comienza el problema
?>
<form name="formulario">
<label>Abono</label>
<input type="number" name="monto_pagar" placeholder="Monto a abonar" onKeyUp="operacion()">
<br>
<?php while ($i <= $cuotas_pendientes) {
$id = "id_cuota".$i; ?>
<!--EN CADA ITERACION CAMBIO EL NOMBRE DEL CHECKBOX Y DEL ID-->
<input name="checkbox<?php echo $i; ?>" type="checkbox" onClick="operacion()" id="<?php echo $id; ?>">
<label for="<?php echo $id; ?>"><?php echo "Cuota ".$i.": ".$precio?></label>
<br>
<!--He colocado la funcion dentro del WHILE ya que el ID va cambiando en cada iteracion-->
<!--Lo intente poner despues de la funcion y obtengo el mismo resultado no deseado-->
<script type="text/javascript">
function operacion() {
caja = document.forms["formulario"].elements;
var numero1 = Number(caja["monto_pagar"].value);
$("#<?php echo $id; ?>").on('change', function(){
this.value = this.checked ? <?php echo $precio; ?> : 0;
}).change();
var numero2 = Number(caja["checkbox<?php echo $i; ?>"].value);
caja["total_id"].value = parseInt(numero1)+parseInt(numero2);
}
</script>
<?php $i++; } ?>
<label>TOTAL</label>
<input type="text" name="total_id" placeholder="0">
</form>