2016-02-15 3 views
1

После нажатия кнопки расчета, его не показывая возвращаемое значение, скорее показывая эту ошибку: «Uncaught ReferenceError: calculateTotal не определен». Я очень новичок в JavaScript. Пожалуйста помоги.Uncaught ReferenceError: calculateTotal не определен

HTML:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <title>2</title> 
     <meta charset="utf-8"/> 
     <script type="text/javascript" src="2.js"></script> 
    </head> 
    <body> 
     <div id="page"> 
     <div id="header"> 
      <h1> 02 </h1> 
     </div> 
     <div id="body"> 
      <p>You probably want to retire someday so let's get started!</p> 
       <form name="retirement savings" action="#" OnClick="calculateTotal(amountNeeded.value, investNo, annContribute,inrate)"> 
        How much money do you need to retire: <input type="text" name="savingsGoal"><br><br> 
        Initial Investment: <input type="text" name="initialInvestment"><br><br> 
        Annual Contribution: <input type="text" name="annualContribution"><br><br> 
        Expected Interest Rate: Select from the following please:<br><br> 
         <input type="radio" name="interestRate" value="1percent">1 Percent<br> 
         <input type="radio" name="interestRate" value="1.5percent">1.5 Percent<br> 
         <input type="radio" name="interestRate" value="2percent">2 Percent<br> 
         <input type="radio" name="interestRate" value="2.5percent">2.5 Percent<br> 
         <input type="radio" name="interestRate" value="3percent">3 Percent<br> 
         <input type="radio" name="interestRate" value="3.5percent">3.5 Percent<br> 
         <input type="radio" name="interestRate" value="4percent">4 Percent<br> 
         <input type="radio" name="interestRate" value="4.5percent">4.5 Percent<br> 
         <input type="radio" name="interestRate" value="5percent">5 Percent<br> 
         <input type="radio" name="interestRate" value="5.5percent">5.5 Percent<br> 
         <input type="radio" name="interestRate" value="6percent">6 Percent<br> 
         <input type="radio" name="interestRate" value="6.5percent">6.5 Percent<br><br> 
         <input type="button" onClick="calculateTotal(savingsGoal.value, initialInvestment, annualContribution,interestRate);" value="Calculate"> <input type="reset"> 
       </form> 
       <br> 
       <hr> 
       <p>You can retire in years</p> 
       <p>with in the bank</p> 
       <hr>     
     </div> 
     <div id="footer"><br> 
     <a href="../index.html">Return to Main Menu</li> 
     </div> 
    </body> 
</html> 

JS:

/*Interest Radio Button*/ 
var interest_rate= new Array(); 
interest_rate["1percent"]=1; 
interest_rate["1.5percent"]=1.5; 
interest_rate["2percent"]=2; 
interest_rate["2.5percent"]=2.5; 
interest_rate["3percent"]=3; 
interest_rate["3.5percent"]=3.5; 
interest_rate["4percent"]=4; 
interest_rate["4.5percent"]=4.5; 
interest_rate["5percent"]=5; 
interest_rate["5.5percent"]=5.5; 
interest_rate["6percent"]=6; 
interest_rate["6.5percent"]=6.5; 


function getIntrestRate() { 
    var interestRadio = document.getElementsByName('interestRate'); 

    for (i=0; i < interestRadio.length; i++) { 
     if (interestRadio[i].checked) { 
      user_input = interestRadio[i].value; 
     } 
    } 

    return interest_rate[user_input]; 
} 

/*Calculation*/ 

function calculateTotal(savingsGoal.value, initialInvestment.value, annualContribution.value, interstRate.value)(){ 
if ((document.calc.savingsGoal.value == null || document.calc.savingsGoal.length == 0) || 
    (document.calc.initialInvestment.value == null || document.calc.initialInvestment.length == 0)|| 
    (document.calc.annualContribution.value == null || document.calc.rate.annualContribution.length == 0)){ 
    alert("Please fill in required fields"); 
    return false; 
} 

else 
{ 
var amount = document.calc.savingsGoal.value; 
var invest = document.calc.initialInvestment.value; 
var yearly = document.calc.annualContribution.value/1200; 
var interest_rate= document.calc.getInterestRate.value; 
document.calc.pay.value = amount * interest_rate/(1 - (1/(1 + intr), yearly))); 
} 
} 

ответ

3

Ваша функция имеет invalid definition. У вас есть дополнительные () после параметров внутри ()

function calculateTotal(savingsGoal.value, initialInvestment.value, 
annualContribution.value, interstRate.value)(){ 
              //^^remove this 

Update

Несколько моментов, которые я только что отметил, который остается недействительным в вашем случае. Так что просто просмотрите код, показанный в этом fiddle. Я обновил оба html и js. Я изменил логику получения значений до function .. Его параметр меньше function сейчас. Также getIntrestRate() - это функция, и вы пытались получить к ней доступ в виде переменной/элемента, а способ, которым вы звонили, был неправильным. Существует орфографическая ошибка, то есть getInterestRate. Просто пройдите через скрипку и обратите внимание, что ее не полностью functional. Не уверен, что вы получаете в intr переменной в конце.

+0

Да, я согласен с этим. Также вы можете удалить параметры из определения функции, если вы не используете их в определении funtion. Используйте как функцию calculateTotal() { –

+0

Я удалил that.but все еще получаю эту ошибку. Также эта ошибка: «Непредвиден SyntaxError: Неожиданный токен». –

+0

@FarhanIshraq .. Ваш код выглядит немного поспешным .. Это не способ сделать это. –

1

calculateTotal Функция не определена должным образом, поскольку в ее сигнатуре есть синтаксическая ошибка.

сделать

function calculateTotal(savingsGoal, initialInvestment, annualContribution, interstRate){ 

вы не можете получить доступ к свойству объекта здесь при определении метода.

Также есть дополнительная скобка ().

0

Я думаю, что Вы не включить файл Jquery библиотеки, чтобы вы включить Jquery файл библиотеки на заголовок его работы

https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js 

или искать последнюю версию файла библиотеки Jquery включить.

Смежные вопросы