Estoy tratando de hacer una calculadora en tiempo real basada en entradas de formulario, cuando uso un div de muestra funciona, pero parece que me falta algo cuando intento imprimir el total dentro de una entrada...
Solución de marcado de trabajo:
<input id='first' type="text" class="form-control formBlock" name="bus_ticket" placeholder="Bus Ticket..." required/><br /> <input id='second' type="text" class="form-control formBlock" name="plane_ticket" placeholder="Plane Ticket..." required/><br /> <input id='third' type="text" class="form-control formBlock" name="hotel_expenses" placeholder="Hotel Expenses..." required/><br /> <input id='fourth' type="text" class="form-control formBlock" name="eating_expenses" placeholder="Eating Expenses..." required/><br /> Total : <span id="total_expenses"></span>Guión de trabajo
$('input').keyup(function(){ // run anytime the value changes var firstValue = parseFloat($('#first').val()); // get value of field var secondValue = parseFloat($('#second').val()); // convert it to a float var thirdValue = parseFloat($('#third').val()); var fourthValue = parseFloat($('#fourth').val()); $('#total_expenses').html(firstValue + secondValue + thirdValue + fourthValue); // add them and output it });Marcado no operativo
<input id='total_expenses' type="text" class="form-control formBlock" name="funding" placeholder="Total Expenses..."/>Guión que no funciona
$('input').keyup(function(){ // run anytime the value changes var firstValue = parseFloat($('#first').val()); // get value of field var secondValue = parseFloat($('#second').val()); // convert it to a float var thirdValue = parseFloat($('#third').val()); var fourthValue = parseFloat($('#fourth').val()); document.getElementById('#total_expenses').value(firstValue + secondValue + thirdValue + fourthValue); // add them and output it });Has estado confundiendo los códigos Javascript y jQuery.
// Wrong code: document.getElementById('#total_expenses').value(sum) //Correct code: document.getElementById('total_expenses').value() = sum Además, cambie parseFloat a Number para que no obtenga NaN cuando al menos uno de sus campos de entrada esté en blanco.
BONIFICACIÓN: cambie su <input type="text" /> a <input type="number" /> para evitar entradas "no numéricas".
Puedes probar este código jquery
var totalValue = firstValue + secondValue + thirdValue + fourthValue; $('#total_expenses').val(totalValue);Primero, al usar getElementById puede omitir el #. En segundo lugar, la asignación de un valor a una entrada usando Vanilla JS se realiza mediante una asignación simple y no una llamada de función. Entonces esa línea debería verse así:
document.getElementById('total_expenses').value = firstValue + secondValue + thirdValue + fourthValue;