2012-05-08 11 views
0

私はJavaScriptが初めてで、できることと使い方を学ぼうとしています。innerHTMLで複数の結果を返す

計算結果として複数の結果を返すことは可能ですか?

私はクラスプロジェクトのための電卓に取り組んでいます。

Interest rate

total amount borrowedmonthly repayment

これまでのところ、私はそれがページ上のdivに毎月の返済を表示するために取得するために管理している:私はそれがやりたいことは、私のページ上の3つの値が返されています1つの計算の結果としてページ上に3つすべてを表示できるようにしたいと考えています。

これは可能ですか?ここで

は、私がこれまでに出ているものです: HTML: <p><input type="button" onclick="main();" value="Calculate"></p>

はJavaScript:

function main() 
{ 

var userInput1 = 0; 
var userInput2 = 0; 
var displayResult; 


userInput1 = document.getElementById("loan_amount").value; 
userInput1 = parseFloat(userInput1); 
userInput2 = document.getElementById("loan_term").value; 
userInput2 = parseFloat(userInput2); 

displayResult = calcLoan(userInput1,userInput2); 
document.getElementById("Result1").innerHTML=displayResult; 

} 

function calcLoan(userInput1,userInput2) 
{ 
var interest =0; 


    if (userInput1 <1000) 
    { 
    alert("Please enter a value above £1000") 
    } 
    else if (userInput1 <= 10000) 
    { 
    interest = 4.25 + 5.5; 
    } 
    else if (userInput1 <= 50000) 
    { 
    interest = 4.25 + 4.5; 
    } 
    else if (userInput1 <= 100000) 
    { 
    interest = 4.25 + 3.5; 
    } 
    else 
    { 
    interest = 4.25 + 2.5; 
    } 


var totalLoan = 0; 


    totalLoan = userInput1 +(userInput1*(interest/100))*userInput2; 

var monthlyRepayment = 0; 
var monthly; 


    monthlyRepayment = totalLoan/(userInput2*12); 
    monthly=monthlyRepayment.toFixed(2); 


    alert("Interest Rate = " + interest + "%" +" "+"Total Loan amount = " + "£"+ totalLoan +" "+ "Your monthly repayment is = " + " " + "£"+ monthly); 

return monthly; 

} 

誰もが正しい方向に私を指すことができれば、それは素晴らしいことです!

答えて

1

複数のカスタムフィールドを使用して変数を作成し、それらを関数間で渡すことができます。したがって、あなたの関数は次のようになります:

function main() 
{ 
    ... 

    displayResult = calcLoan(userInput1,userInput2); 
    document.getElementById("Result1").innerHTML = displayResult.interest; 
    document.getElementById("Result2").innerHTML = displayResult.totalLoan; 
    document.getElementById("Result3").innerHTML = displayResult.monthly; 
} 

function calcLoan(userInput1,userInput2) 
{ 
    ... 

    alert("Interest Rate = " + interest + "%" +" "+"Total Loan amount = " + "£"+ totalLoan +" "+ "Your monthly repayment is = " + " " + "£"+ monthly); 

    var result; 
    result.interest = interest; 
    result.totalLoan = totalLoan; 
    result.monthly = monthly; 

    return result; 
} 

ID1つのResult1、Result2、Result3のdiv要素を追加することを忘れないでください。

<div id="Result1"></div> 
<div id="Result2"></div> 
<div id="Result3"></div> 
+0

ありがとう、私はそれを行って、あなたに知らせるよ – user1361276

+0

私はこの方法を試しました。エラーコンソールは 'result result undefined 'というエラーを出力します。 result.interest = interest;結果は総計= 0です。 result.monthly = monthly; ' – user1361276

+0

OK。 'var result;'を 'var result = [];'に変更します。今それは動作するはずです。 – mostar

関連する問題