【发布时间】:2015-04-17 21:16:20
【问题描述】:
尝试学习 JS 并且似乎进展顺利,但在此表单验证上卡住了......它应该验证文本框没有留空或使用默认值。验证返回false时可以弹出警报,但是在字段中输入信息后,表单不返回true提交..
感谢任何帮助。见以下代码:
function validateFunc() {
var nameField = document.forms[0].visitor_name.value
var emailField = document.forms[0].email.value
var phoneField = document.forms[0].phone.value
var areaField = document.forms[0].area.value
if (nameField || emailField || phoneField || areaField === "") {
window.alert("Please fill out all fields!");
return false;
}
else {
return true
}
}
<form action="FormProcessor.html" method="get" enctype="application/x-www-form-urlencoded" onsubmit= "return validateFunc()">
<p>Name<br />
<input type="text" name="visitor_name" size="50"/ value="Enter your name" onclick="if (this.value == 'Enter your name') this.value='';">
</p>
<p>E-mail Address<br />
<input type="text" name="email" size="50" value="Enter your email address" onclick="if (this.value == 'Enter your email address') this.value='';"/>
</p>
<p>Phone<br />
<input type="text" name="phone" size="50" value="Enter your phone number" onclick="if (this.value == 'Enter your phone number') this.value='';"/>
</p>
<p>Area of town<br />
<input type="text" name="area" size="50" value="What area of town are you interested in?" onchange="noEmptyBoxes()" onclick="if (this.value == 'What area of town are you interested in?') this.value='';"/>
</p>
<p>Property
<select name="property_type">
<option value="unselected">Select a property type</option>
<option value="condo">Condos</option>
<option value="single">Single Family Homes</option>
<option value="multi">Multifamily Homes</option>
<option value="mobile">Mobile Homes</option>
<option value="land">Land</option>
</select>
Sq. feet <input type="text" name="feet" size="5" value="???" onclick="if (this.value == '???') this.value='';"/>
</p>
<p>Bedrooms <input type="text" name="bedrooms" size="5" value="???" onclick="if (this.value == '???') this.value='';"/>
Maximum Price <input type="text" name="price" size="12" value="$$$" onclick="if (this.value == '$$$') this.value='';"/>
</p>
<p>How should we contact you?
<input type="radio" name="contactHow" value="call_me"/>Call me
<input type="radio" name="contactHow" value="e-mail_me"/>Email me
</p>
<p>
<input type="submit"/>
</p>
</form>
【问题讨论】:
-
if (nameField || emailField || phoneField || areaField === "")。你认为这段代码有什么作用? -
学习Logical Operators可能有用吗?
-
@Teemu 对于像我这样的 js 新手来说绝对有用。谢谢!
标签: javascript forms validation return onsubmit