当表单提交时,如果输入框为空,我们可以使用jQuery来检测并给这些空输入框添加特定的CSS类(通常用于高亮显示错误或提醒用户)。这是一种常见的前端表单验证技术。
$(document).ready(function() {
$('form').on('submit', function(e) {
// 查找所有必填的输入框
$('input[required]').each(function() {
if ($(this).val() === '') {
// 为空时添加error类
$(this).addClass('error');
// 阻止表单提交
e.preventDefault();
} else {
// 不为空时移除error类
$(this).removeClass('error');
}
});
});
});
$(document).ready(function() {
$('form').on('submit', function(e) {
let hasError = false;
// 清除所有之前的错误状态
$('input').removeClass('error');
$('.error-message').remove();
// 检查每个必填字段
$('input[required]').each(function() {
if ($(this).val().trim() === '') {
$(this).addClass('error');
// 添加错误提示
$(this).after('<span class="error-message">此字段不能为空</span>');
hasError = true;
}
});
if (hasError) {
e.preventDefault();
}
});
// 当用户开始输入时移除错误状态
$('input').on('input', function() {
if ($(this).hasClass('error')) {
$(this).removeClass('error');
$(this).next('.error-message').remove();
}
});
});
.error {
border: 1px solid red;
background-color: #ffeeee;
}
.error-message {
color: red;
font-size: 0.8em;
margin-left: 5px;
}
可以结合HTML5的表单验证属性(如required
、pattern
等)来增强验证功能,或者使用jQuery Validation Plugin等现成的验证库来简化开发。