简体   繁体   中英

Javascript function not defined in jQuery

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.

Try this:

Give your form a name and ID eg '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.

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.

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);
}

您必须将depositCal函数定义排除在$(document).ready() ,因为首先加载整个文档,然后调用$(document).ready()因此,在加载表单时,浏览器会发现depositCal未定义因为它是在文档完全加载后定义的...因此,将depositCal定义保留在全局范围内

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM