2012-04-13 98 views
3

我想在表單中驗證輸入字段'putime',因爲即使'putime'輸入框爲空,結果也會計算,並且nightSurcharges也會添加到成本中。所以我想驗證'putime'是否爲空,否則腳本無用。在提交表單之前驗證輸入字段

function TaxiFare() { 
// calculates taxi fare based upon miles travelled 
// and the hour of the day in military time (0-23). 

var baseFare = 14; 
var costPerMile = 7.00; 
var nightSurcharge = 20.50; // 9pm to 6am, every night //its flat 20.50 and not per mile 

var milesTravelled = Number(document.getElementById("miles").value) || 0; 
if ((milesTravelled < 1) || (milesTravelled > 200)) { 
alert ("You must enter 1 - 200 miles"); 
document.getElementById("miles").focus(); 
return false; 
} 

var pickupTime = Number(document.getElementById("putime").value) || 0; 
if ((pickupTime < 0) || (pickupTime > 23) || (pickupTime==null)) { // note the hours are 0-23. There is no 24 hour, midnight is 0 hours 
alert ("The time must be 0-23 hours"); 
document.getElementById("putime").focus(); 
return false; 
} 

var cost = baseFare + (costPerMile * milesTravelled); 
// add the nightSurcharge to the cost if it is after 
// 8pm or before 6am 
if (pickupTime >= 21 || pickupTime < 6) { 
cost += nightSurcharge; 
} 
document.getElementById("result").innerHTML = "Your taxi fare is: $. " + cost.toFixed(2); 
} 


And here is the Form from HTML 


    <form> 
Miles for Journey <input type="text" id = "miles" required><br> 
Pickup Time <input type = text id = "putime" required><br><br> 
<input type="button" value="Calculate Fare" onclick="TaxiFare()"> 
<input type="reset" value="Clear"><br><br> 
<span id = "result"></span> 
</form> 

我試了很多,但無濟於事....任何幫助是歡迎的。提前致謝!

回答

2

如何添加事件處理程序的形式,在document.forms[0].submit = validateFunction;

喜歡那裏validateFunction可能是這樣的:

function validateFunction() 
{ 
    var allIns = this.getElementsByTagName('input'); 
    if(allIns.namedItem('putime').value == '') 
    { 
     alert('silly'); 
     return false; 
    } 
    //and other checks go here, too 
} 
相關問題