简体   繁体   English

如何使用JavaScript验证HTML表单?

[英]How do you validate an HTML form using JavaScript?

I am creating a basic survey using the tag, but I am having trouble with using JavaScript to validate the form. 我正在使用标记创建基本调查,但是在使用JavaScript验证表单时遇到了麻烦。 I would like it to check all forms and not just one. 我希望它能检查所有表格,而不仅仅是表格。 Please help! 请帮忙! Thanks! 谢谢! Here is the code: 这是代码:

<!DOCTYPE html>
<html>
<head>
<title>SurveyBot v1</title>
</head>
<body>
<form action="">
What is your first name?: <input type="text" name="firstname"><br>
What is your last name?: <input type="text" name="lastname">
</form>
<h5>What is your gender?</h5>
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
<h5>Which of the following vehicles do you own? (Check all that apply):</h5>
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Scooter">I have a scooter<br>
<input type="checkbox" name="vehicle" value="Quad">I have a quad<br>
<input type="checkbox" name="vehicle" value="Snowmobile">I have a snowmobile<br>
<input type="checkbox" name="vehicle" value="Skateboard">I have a skateboard<br>
<input type="checkbox" name="vehicle" value="Car">I have a car 
</form>
<h5>Which of the following car brands do you drive as your primary car?</h5>
<form action="">
<select name="cars">
<option value="none">None</option>
<option value="other">Other</option>
<option value="volvo">Volvo</option>
<option value="kia">Kia</option>
<option value="fiat" selected>Fiat</option>
<option value="audi">Audi</option>
<option value="honda">Honda</option>
<option value="mitsubishi">Mitsubishi</option>
<option value="toyota">Toyota</option>
<option value="ford">Ford</option>
</select>
</form>
<h5>Please check the box that says "I have finished" and press submit. Thank you for taking the survey.</h5>
<form name="input" action="html_form_action.html" method="get">
<input type="checkbox" name="finished" value="I am finished">I have finished<br>
<br><br>
<input type="submit" value="Submit">
</body>
</html>

Just add JavaScript function call near submit button. 只需在“提交”按钮附近添加JavaScript函数调用即可。

<input type="submit" onclick="return validateForm(this.form);" />

Make JavaScript function. 使JavaScript功能。 Take help from following link: link or you can google some examples. 从以下链接获取帮助: 链接,或者您可以在Google上搜索一些示例。

Moreover, You need to put all stuffs inside single <form></form> tags to make it work. 而且,您需要将所有内容放入单个<form></form>标记中才能使其正常工作。 Else you need a workaround that makes your work more tedious. 否则,您需要一种变通方法,使您的工作更加乏味。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM