Reputation: 622
I have problems with a simple bit of code. I'm trying to take a value from an input field and then do a simple calculation. The calculation is supposed to take place with an onSubmit
command and then append it to a p
tag.
HTML:
<h1 class="titleHead">Calculator</h1>
<form method="POST" action="#" onSubmit="depositCal()">
<input type="text" name="money" id="money">
<input type="submit" value="How much" onSubmit="">
</form>
<div>
<p class="answer"></p>
</div>
Javascript:
$(document).ready(function() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
function depositCal() {
$('.answer').append(finalNumber);
}
})
I get back function not defined when it runs.
I know this is probably very simple but any help would be greatly appreciate.
Upvotes: 0
Views: 66
Reputation: 3299
Try this:
Give your form a name and ID e.g. 'myForm'
JS
$('#myForm').submit(function(e){
e.preventDefault();
var numberOne = $('#money').val();
var numberTwo = 4;
var finalNumber = numberOne + numberTwo;
$('.answer').append(finalNumber);
});
e.preventDefault() - stops the form from submitting (thus refreshing the page) and the function is only fired when submit is clicked.
Addition
numberOne is getting it's value from a form field so it sees it as a string. To prevent this use this line instead:
var numberOne = parseFloat($('#money').val());
Which forces the value to be a (float) number.
Upvotes: 2
Reputation: 4089
You have to keep the depositCal function definition out of $(document).ready()
,because first the whole document is loaded,then $(document).ready()
is called.So while loading the form,browser finds depositCal as undefined as it is defined after document is fully loaded......So keep the depositCal definition in global scope
Upvotes: 0
Reputation: 28513
I think you don't need $(document).ready
here and do calculation of finalNumber
inside function so that it will give you the correct value of money
input, otherwise you will get NaN
or empty value-
function depositCal() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
$('.answer').append(finalNumber);
}
Upvotes: 0
Reputation: 59232
You need to declare the function in global scope if you want to use it in inline js
$(document).ready(function() {
var numberOne = $('#money').val(),
numberTwo = 4;
var finalNumber = numberOne + numberTwo;
})
function depositCal() {
$('.answer').append($('#money').val() + 4);
}
You could also make it a global function by attaching the function
to window
object.
Upvotes: 1