我試圖讓這個腳本能夠正常工作,但是它在最後一次警報的某個地方失敗了。該腳本應該從表單中提取所有內容,然後將結果作爲警告框進行吐出。我很確定我的html是正確的。JavaScript的幫助!腳本不能正常工作
function calcServiceTotal() {
var animalName = document.getElementById("name").value;
var ownerName = document.getElementById("owner").value;
var currentDate = document.getElementById("date").value;
var choosenService = document.getElementById("service");
var serviceName = choosenService.options[choosenService.selectedIndex].text;
var serviceCost = document.getElementById("value").value;
var taxCost = serviceCost * 0.07;
var totalCost = serviceCost + taxCost;
if (animalName == null || animalName == "")
{
alert("Please give us your pet's name.");
return false;
}
else if (ownerName == null || ownerName == "")
{
alert("Please give us your name.");
return false;
}
else if (currentDate== null || currentDate == "")
{
alert("Please give us a date.");
return false;
}
else
{
alert("Pet's Name:" + animalName + '\n' + "Owner's Name:" + ownerName + '\n' + "Service:" + choosenService + '\n' + "Cost: $" + serviceCost.toFixed(2) + '\n' + "Tax: $" + taxCost.toFixed(2) + "Total Cost:" + totalCost.toFixed(2));
}
}
這裏是相關的html代碼。
<table width="339" border="0">
<tr>
<td width="329"><strong>Patient Information</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Name:
<label for="textfield"></label> <input type="text" name="textfield" id="name" /></td>
</tr>
<tr>
<td>Owner:
<input type="text" name="textfield2" id="owner" /></td>
</tr>
<tr>
<td>Date:
<input type="text" name="textfield3" id="date" /></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><strong>Services</strong></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><form id="form1" name="form1" method="post">
Select a Service:
<label for="select"></label>
<select name="select" id="service">
<option>Basic Appointment - $50</option>
<option>Extended Appointment - $75</option>
<option>Vacination - $25</option>
<option>Grooming - $35</option>
<option>Bathing - $35</option>
</select>
</form></td>
</tr>
<tr>
<td>Service Fee (from above):
<label for="textfield4"></label>
<input type="text" name="textfield4" id="value" />
</td>
</tr>
<tr>
<td><form id="form2" name="form2" method="post" action="">
<input type="button" onclick="calcServiceTotal();" name="button" id="button" value="calculate"/>
</form></td>
</tr>
</table>
歡迎[SO]。請花一些時間來查看[faq]。你可能會注意到,當你寫一個問題時,問題看起來像什麼樣的預覽會出現在問題本身的下面。如果你能確保格式化你的代碼以便表現出來,那將是如此友善。不要太急於提交您的問題太早,請花點時間並在點擊提交按鈕之前仔細查看。 – zzzzBov 2012-03-12 20:24:56
使用真正的調試器。 – 2012-03-12 20:25:13
此外,使用諸如[jsfiddle](http://jsfiddle.net)這樣的服務來解決有大塊HTML,CSS和JS的問題會很有幫助。 – zzzzBov 2012-03-12 20:27:15