Reputation: 13
I'm trying to make a basic ROI calculator and having trouble getting any kind of math function to work. I will only require two user variable inputs and want my coding to pass through a simple math equation and post the answer. The math formula will change once I can get my two input variables to at least multiply against each other.
Upon hitting submit, no output is given and the input fields reset. Clicking reset does clear the fields. I want the input (#output) to display the answer.
I don't care about CSS or final formula at this point.
HTML Type:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="calculator.js" type="text/javascript"></script>
<title>Calculator</title>
</head>
<body>
<form id="calculator">
<input type="text" id="Occupancy" name="occupancy">
<input type="text" id="rooms" name="rooms">
<button id="submit" type="submit" name="submit">Submit</button>
<button id="reset" type="reset" name="reset">Reset</button>
<input type="text" id="output" name="output">
</form>
</body>
</html>
JavaScript code below:
// JavaScript Document
$(document).ready(function() {
$('#calculator').submit(function() {
var occupancy = $('#Occupancy').val();
var rooms = $('#rooms').val();
var output =occupancy * rooms;
output = output.toFixed(2);
$('#output').val(output);
});
});
Upvotes: 1
Views: 730
Reputation: 1427
If there's no requirement to submit the form:
$('#calculateButton').click(function() {
var occupancy = $('#Occupancy').val();
var rooms = $('#rooms').val();
var output = +occupancy * +rooms;
$('#output').val(output.toFixed(2));
});
Upvotes: 0
Reputation: 284
Try this:
// JavaScript Document
$(document).ready(function() {
$('#submit').click(function() {
var occupancy = $('#Occupancy').val();
var rooms = $('#rooms').val();
var output =occupancy * rooms;
output = output.toFixed(2);
$('#output').val(output);
});
});
Upvotes: 0
Reputation: 74028
Your script works fine. What happens is, the script runs and calculates the result. But then, the form is submitted to the server and reloads the page.
To prevent this, you must prohibit the form from submitting to the server
$('#calculator').submit(function(evt) {
evt.preventDefault();
var occupancy = $('#Occupancy').val();
var rooms = $('#rooms').val();
var output = occupancy * rooms;
output = output.toFixed(2);
$('#output').val(output);
});
See JSFiddle
Upvotes: 3
Reputation: 2290
try to change
var occupancy = $('#Occupancy').val();
to var occupancy = parseFloat($('#Occupancy').val());
and var rooms = $('#rooms').val();
to var rooms = parseFloat$('#rooms').val());
Upvotes: 0