Home >Web Front-end >JS Tutorial >How to implement form checkbox validation in JavaScript

How to implement form checkbox validation in JavaScript

青灯夜游
青灯夜游Original
2018-11-09 17:38:223584browse

The content of this article is to introduce how to implement the check box verification of the form in js. When the form is submitted, it is judged whether the check box is selected. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

js implements form check box verification

On the website, when we submit some forms, such as registration, etc., there will be a request at the bottom for people to "accept the terms and conditions" ” or something similar. Basically if you don't agree (don't select), you can't submit the form.

So how to implement such a function?

It’s actually very simple. Using vanilla JavaScript, we can prevent form submission, as shown below:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js实现表单的复选框验证</title>
		<script type="text/javascript">
			function checkForm(form) {
				if(!form.terms.checked) {
					alert("请注明接受条款和条件。");
					form.terms.focus();
					return false;
				}
				return true;
			}
		</script>
	</head>

	<body>

		<form id="example1" method="POST" action="" onsubmit="return checkForm(this) && alert(&#39;成功!&#39;);">

			<p><input id="field_terms" type="checkbox" name="terms">
				<label for="field_terms">我接受 <u>条款和条件</u></label></p>
			<span><input type="submit"></span>

		</form>

	</body>

</html>

Rendering:

How to implement form checkbox validation in JavaScript

You’re done, you can try it yourself!

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

The above is the detailed content of How to implement form checkbox validation in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn