Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real Time Javascript Calculation Based On Form Inputs

I'm trying to make a real-time calculator based on form inputs, when I use a sample div it works but I seem to be missing something when I try to print the total inside an input...

Working Markup Solution:

 <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>

Working Script

$('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
});

Non-Working Markup

<input id='total_expenses' type="text" class="form-control formBlock" name="funding"  placeholder="Total Expenses..."/>

Non-Working Script

$('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
});
like image 731
Sebastian Farham Avatar asked Dec 18 '22 09:12

Sebastian Farham


2 Answers

Here's a working JSFiddle.

You've been confusing Javascript and jQuery codes.

// Wrong code:
document.getElementById('#total_expenses').value(sum)
//Correct code:
document.getElementById('total_expenses').value() = sum

Also, change parseFloat to Number so you don't get NaN when at least one of your input fields is blank.

BONUS: change your <input type="text" /> to <input type="number" /> to prevent "non-numerical" inputs.

like image 115
ITWitch Avatar answered Dec 24 '22 02:12

ITWitch


You can try this jquery code

var totalValue = firstValue + secondValue + thirdValue + fourthValue;
$('#total_expenses').val(totalValue);
like image 39
bharat savani Avatar answered Dec 24 '22 01:12

bharat savani