Jquery 不同输入的验证
我想验证代码中的不同输入,但每个输入都会显示错误消息Jquery 不同输入的验证,jquery,validation,Jquery,Validation,我想验证代码中的不同输入,但每个输入都会显示错误消息 $.each($('.input'), function(){ if ($('.input').val() == "") $(this).css('border' , 'solid red'); $(this).after('<span class="error">Name fehlt</span>'); $
$.each($('.input'), function(){
if ($('.input').val() == "")
$(this).css('border' , 'solid red');
$(this).after('<span class="error">Name fehlt</span>');
$(this).focus()
})
`我认为你应该这样做:
$('.input').each(function () {
if ($(this).val() == "") {
$(this).css('border', 'solid red');
$(this).after('<span class="error">Name fehlt</span>');
$(this).focus()
}
})
$。每个都对您有相同的作用。不过,我认为以上内容更具可读性。但那只是我。这里有几件事。每个都在选择器上工作,因此您只需执行以下操作:
$(".input").each(...)
第二,这就是为什么消息总是出现在if语句中,因为if语句缺少大括号,所以它只会应用于下一个语句:$this.css'border','solid red'
最后,您可以将jQuery调用链接在一起:
$(".input").each(function() { // Nicer syntax
// Refer to $(this) to get the value of the CURRENT input
if($(this).val() == "") { // Don't forget your braces
$(this).css("border", "solid red")
// Method chaining
.after('<span class="error">Name fehlt</span>');
.focus();
}
});
假设您有多个输入字段,可能您需要如下内容:
validateInput($('.input-name'), 'Name fehlt');
function validateInput(input,errormsg){
if (input.val() == "") {
input.css('border', 'solid red');
input.after('<span class="error">'+errormsg+'</span>');
input.focus()
}
}
validateInput($('.input-street'),'Strasse fehlt');
也许更进一步的改进是将错误消息移动到输入字段上的数据属性:
<input type="text" data-required-message="Name fehlt" class="input-name" />
您可以在每个循环中使用标志:
fdo收到的错误消息是什么?如果要验证多个输入,您可能希望将其转换为一个函数,将输入元素和错误消息作为参数-如果您只有要验证的名称,则不应使用每个名称
$(this).data('required-message')
var isValid = true;
$(".input").each(function() {
var $this = $(this);
if ($this.val() === '' && isValid) {
$this.css('border', 'solid red')
.after('<span class="error">Name fehlt</span>')
.focus();
isValid = false;
return false;
}
});
return isValid;