简体   繁体   中英

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. 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.

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

Make JavaScript function. Take help from following link: link or you can google some examples.

Moreover, You need to put all stuffs inside single <form></form> tags to make it work. Else you need a workaround that makes your work more tedious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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