Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Real Time Javascript Calculation Based On Form Inputs
<!DOCTYPE html>
<html>
<head>
<title>Tes Form</title>
</head>
<body>
<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 />
<br /><br />
Total: <span id="total_expenses1"></span>
<br />
Total: <input id='total_expenses2' type="text" class="form-control formBlock" name="funding" placeholder="Total Expenses..."/>
<br /><br />
For:
<a target="_blank" href="http://stackoverflow.com/questions/42730666/real-time-javascript-calculation-based-on-form-inputs">a stackoverflow question</a>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript">
$('input').keyup(function(){ // run anytime the value changes
var firstValue = Number($('#first').val()); // get value of field
var secondValue = Number($('#second').val()); // convert it to a float
var thirdValue = Number($('#third').val());
var fourthValue = Number($('#fourth').val());
$('#total_expenses1').html(firstValue + secondValue + thirdValue + fourthValue); // add them and output it
document.getElementById('total_expenses2').value = firstValue + secondValue + thirdValue + fourthValue;
// add them and output it
});
/*
$('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
});*/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.