我是JavaScript新手,我試圖創建一個看似簡單的表單。但由於某種原因,我無法讓它工作。我知道這對入門級javascripters來說應該是一件容易的事,但我無法弄清楚。我今天已經嘗試了很多解決方案,但是我一直無法實現它。任何幫助你們能給將不勝感激:)用於計算學期課程費用的Javascript表格
我試圖建立一個估計翹課成本的形式:
(http://jsfiddle.net/Gt2vK/2/)
function calculateCost() {
// enter annual tuition
var $annualTuition = parseInt($('#annual_tuition').val(), 10);
// tuition per semester
var semesterTuition = $annualTuition/3;
// total number of credits for semester
var $semesterCredits = parseInt($('#semester_credits').val(), 10);
// cost of a single credit
var singleCreditCost = semesterTuition/$semesterCredits;
// total credits for class being skipped
var $skippedTotalCredits = parseInt($('#skipped_total_credits').val(), 10);
// total cost for class being skipped
var skippedTotalCreditsCost = $skippedTotalCredits * singleCreditCost;
// total number of days in semester for class being skipped
var $skippedTotalDays = parseInt($('#skipped_total_days').val(), 10);
// (total cost of class)/(total number of class days in semester) = cost of class
var skippedSingleClassCost = skippedTotalCreditsCost/$skippedTotalDays;
}
$(function(){
$('#cost').on('click', function(){
$('#costTotal').html(calculateCost);
// why the heck doesnt this work?!?
alert(calculateCost);
});
});
和我的HTML :
<form id="costForm" action="#" onsubmit="#">
<div>
<label for="annual_tuition">Annual Tuition:</label>
<input type="text" name="annual_tuition" id="annual_tuition" value="" tabindex="1">
</div>
<div>
<label for="semester_credits">Semester Credits</label>
<input type="text" name="semester_credits" id="semester_credits" value="" tabindex="1">
</div>
<div>
<label for="skipped_total_credits">Skipped Total Credits</label>
<input type="text" name="skipped_total_credits" id="skipped_total_credits" value="" tabindex="1">
</div>
<div>
<label for="skipped_total_days">Skipped Total Days</label>
<input type="text" name="skipped_total_days" id="skipped_total_days" value="" tabindex="1">
</div>
<div>
<button id="cost" type="button" >Calculate</button>
</div>
<div id="costTotal"></div>
</form>
1)我沒有看到'calculateCost'被調用的任何地方。 2)這些變量只存在於函數的範圍內,所以它們不能在外部訪問。如果你需要函數的值,你應該調用函數並返回值。我可能錯過了什麼? – Zhihao
請勿嘗試在「提交」按鈕上觸發您的onclick事件。使用按鈕按鈕。 –
doh!對不起(我不知道我在做什麼) –