我创建了简单的表单验证,但没有任何工作。下面是我的表单和javascript的代码。我从教科书中把它拿走了。我有一个提交按钮。当我点击它没有任何反应。我正在使用外部.js文件,并确实包含页面上的部分链接。我非常感谢您的意见。
<form name="reservation" onsubmit="return validate(this);">
<fieldset>
<legend>Reservation</legend>
<br/>
<label>Name*</label>
<br/>
<input type="text" name="txtName" id="txtName" size="60">
<br/><br/>
<label>Date and Time*</label>
<br/>
<input type="text" id="txtDate" name="txtDate" size="40"><a href="javascript:NewCal('txtDate','mmmddyyyy',true,12)"><img src="../Images/cal.gif" width="18" height="18" border="0" alt="Pick a date"></a>
<br/><br/>
<label>Party Size*</label>
<br/>
<input type="text" id="txtParty" name="txtParty" size="20">
<br/><br/>
<label>Phone*</label>
<br/>
<input type="text" id="txtPhone" name="txtPhone" size="40">
<br/><br/>
<label>Email*</label>
<br/>
<input type="text" id="txtEmail" name="txtEmail" size="60">
<br/><br/>
<input type="submit" id="button" value="Submit"/>
<p id="main_text">
*=required
</p>
</fieldset>
</form>
使用Javascript:
function validate(form){
var returnValue=true;
var name = form.txtName.value;
var date = form.txtDate.value;
var party = form.txtParty.value;
var phone = form.txtPhone.value;
var email = form.txtEmail.value;
if (name=="") {
returnValue = false;
alert("Name is a required field");
document.reservation.txtName.focus();
}
if (date=="") {
returnValue = false;
alert("Date is a required field");
reservation.txtName.focus();
}
if (party=="") {
returnValue = false;
alert("Party Size is a required field");
document.reservation.txtName.focus();
}
if (phone=="") {
returnValue = false;
alert("Phone is a required field");
document.reservation.txtName.focus();
}
if (email=="") {
returnValue = false;
alert("Email is a required field");
document.reservation.txtName.focus();
}
alert("Thank for providing your information.\n
We will get back you as soon as possible.");
return returnValue;
}
答案 0 :(得分:-2)
我认为你应该考虑使用jQuery
它更加有效和易于使用!您还应该考虑使用else if()
语句。
var name = $('#txtName').val();
var email = $('#txtEmail').val();
if(name == ""){ alert("Please fill in the name field");
$('#txtName').focus();
return false;
}
else if(email == ""){ alert("Please fill in the email field");
$('#txtName').focus();
return false;
}else{
alert("All good");
return true;
}