检测用户输入的信息是否为空

点击触发

1
2
3
4
5
$('.info-submit').on('click', function(){   //点击触发开始检测
if(checkEmptyInput()){
//信息全部正确,继续执行
}
});

逐个报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function checkEmptyInput() { //检测上传信息
var name = $('.name').val();
var phone = $('.phone').val();
var address = $('.address').val();
if ($.trim(name).length === 0) {
console.log('请输入姓名');
return false;
}
if ($.trim(phone).length === 0) {
console.log('请输入手机号');
return false;
}
if ($.trim(address).length === 0) {
console.log('请输入地址');
return false;
}
return true;
}

一起报错(表单常用报错方式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function checkEmptyInput() { //检测输入信息
var hasError = false;
var nameValue= $('.name').val();
var ageValue = $('.age'). val();
var phoneValue = $('.phone'). val();
if (nameValue.length === 0) {
$('.p2-name-error').css({'opacity': '1'});
hasError = true;
}
if (ageValue.length === 0) {
$('.p2-age-error').css({'opacity': '1'});
hasError = true;
}
if (phoneValue.length === 0) {
$('.p2-tel-error').css({'opacity': '1'});
hasError = true;
}
if((nameValue.length !== 0) && (ageValue.length !== 0) && (phoneValue.length !== 0)){ //所有信息正确
hasError = false;
}

if(hasError) {
return false;
} else {
return true;
}
}