表单提交时,往往我们不能让它为空,所以,有几种方法我们都可用来验证是否为空:
1,用css的required属性
也就是在<input>里加入required=”required” ,比如:
<input type="" required="required" name="" id="" value="" />
2,用JS代码
首先form要加上onSubmit事件,form.**.vlaue要在表单中对应name,比如:
首先在<form>里加入 onsubmit=”return beforeSubmit(this);”
然后:
<script type="text/javascript">
function beforeSubmit(form){
if(form.username.value==''){
alert('用户名不能为空!');
form.username.focus();
return false;
}
return true;
}
</script>
其中,form.username.value==”,的username对应input中 name的值,如果你的name值是其它就改其它。form.username.focus(); 中的username也是对应input中 name的值,这句的意思是在提示错误输入后,鼠标移到该对话框,方便输入
3,使用jQuery方法(通过class验证),需要引用jquery.min.js,比如:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
</head>
<body>
<form>
<!-- input -->
<div>
姓名: <input type="text" name="name" notNull="姓名" class="form-control noNull">
</div>
<br>
<!-- radio -->
<div>
性别:
男<input type="radio" name="sex" value="0" class="noNull" notNull="性别">
女<input type="radio" name="sex" value="1" >
</div>
<br>
<!-- select -->
<div>
年龄:
<select name="age" class="noNull" notNull="年龄">
<option value ="">请选择</option>
<option value ="1">1</option>
<option value ="2">2</option>
</select>
</div>
<br>
<!-- checkbox -->
<div>
兴趣:
打球<input type="checkbox" name="hobby" value="1" class="noNull" notNull="兴趣">
唱歌<input type="checkbox" name="hobby" value="2">
跳舞<input type="checkbox" name="hobby" value="3">
</div>
<br>
<button type="button" class="btn-c" onclick="bubmi()">保存</button>
</form>
<script src="jquery-3.5.1.min.js"></script>
<script type="text/javascript">
function bubmi(){
$(".noNull").each(function(){
var name = $(this).attr("name");
if($(this).val()==""){
alert($(this).attr('notNull')+"不能为空");return false;
}
if($(this).attr("type")=="radio"){
if ($("input[name='"+name+"']:checked").size() < 1){
alert($(this).attr('notNull')+"不能为空!");
return false;
}
}
if($(this).attr("type")=="checkbox"){
if ($('input[name="'+name+'"]:checked').size() < 1){
alert($(this).attr('notNull')+"不能为空!");
return false;
}
}
})
}
</script>
</body>
</html>
点击数:389