分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

检测提交表单内容不能为空JS/jQuery代码(基础)

发布时间:2023-09-06 02:31责任编辑:熊小新关键词:jQuery

方法一:

使用css的required属性

<input type="" required="required" name="" id="" value="" />

方法二:

使用JS代码示例,注意事项:form要加上onSubmit事件,form.xx.vlaue要在表单中对应name

<script type="text/javascript">function beforeSubmit(form){if(form.username.value==‘‘){alert(‘用户名不能为空!‘);form.username.focus();return false;}if(form.password.value==‘‘){alert(‘密码不能为空!‘);form.password.focus();return false;}if(form.password.value.length<6){alert(‘密码至少为6位,请重新输入!‘);form.password.focus();return false;}if(form.password.value!=form.password2.value) {alert(‘你两次输入的密码不一致,请重新输入!‘);form.password2.focus();return false;}return true;}</script><fieldset> ??<legend>用户注册</legend> ???<form method="post" name="form" action="user.do?method=register" onSubmit="return beforeSubmit(this);"> ????<table border="1" width="100%" cellspacing="0" cellpadding="0"> ?????<tr><td><label>用户名:<input type="text" name="username" value=""></label></td></tr> ?????<tr><td><label>密 ??码:<input type="password" name="password" value=""></label></td></tr> ?????<tr><td><label>重复密码:<input type="password" name="password2" value=""></label></td></tr> ?????<tr><td><input value="注册" type="submit"> <input type="reset" value="重置"></td></tr> ??????????</table> ???</form></fieldset>

方法三:

使用jQuery方法,需要引用jquery.min.js

<form action="" id="form"> ??<table align="center"> ?????????<tr> ???????????????<td>名称:</td> ???????????????<td> ?????????????????????<input type="text" name="username" title="名称"> ????????????????????</td> ?????????</tr> ?????????<tr> ???????????????<td>咨询内容:</td> ???????????????<td> ?????????????????????<textarea rows="8" cols="45" title="咨询内容"></textarea> ???????????????</td> ?????????</tr> ?????????<tr> ???????????????<td align="center" colspan="2"> ?????????????????????<input type="button" value="提 交" onclick="check()"> ???????????????</td> ?????????</tr> ??</table></form>function check(){ ???????????var checkform = document.getElementById("form"); ??//获得form表单对象 ???????????for(var i=0;i<form.length;i++){ ??????????????????//循环form表单 ?????????????????if(checkform.elements[i].value==""){ ???????//判断每一个元素是否为空 ?????????????????alert(checkform.elements[i].title+"不能为空!"); ?????????????????checkform.elements[i].focus(); ?????????????//元素获得焦点 ?????????????????return ; ?????????????????} ???????????} ???????????checkform.submit(); ?????}

检测提交表单内容不能为空JS/jQuery代码(基础)

原文地址:https://www.cnblogs.com/colinliu/p/checkform_null.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved