[英]jQuery Validate: Validating multiple forms on single page if has same value
[英]Validating multiple forms with same class using jquery validate
我有一页上大约有 10 个 forms 与相同的 class。 每个表单都应该能够单独验证和发送。 我正在使用 jquery 验证插件。 我无法让它工作,所有的 forms 都在提交第一个。 除此之外,我似乎无法使用 $(this).find('.error').html(error); 在表单中定位错误消息 div;
每个表格如下所示:
<form method="post" class="alertform" action="">
<input type="text" onclick="clearText(this)" value="" class="required email" name="email">
<input type="hidden" value="1000004011320719" name="productid" class="productid">
<input type="submit" class="button" name="button" value="Set alert">
<div class="error"> </div>
</form>
我的 JS:
$('.alertform').each( function(){
$(this).validate({
rules: {
emailadres: {
required: true,
email: true
}
},
messages: {
emailadres: {
required: "Message 1",
minlength: "Message 2",
email: "Message 3"
}
},
errorPlacement: function(error, element) {
$(this).find('.error').html(error);
},
success: function(label) {
label.addClass("valid").text("")
},
submitHandler: function() {
var emailadres = $(this).find("input.email").val();
var productid = $(this).find("input.productid").val();
var dataString = 'emailadres=' + emailadres + '&productid=' + productid;
$.ajax({
type: "POST",
url: "/setalert.php",
data: dataString,
success: function(msg) {
if (msg==1) {
$(this).find(".email").attr("value", "");
$(this).find('.error').html("Pricealert set.")
}
else {
$(this).find('.error').html("Oops.")
}
}
});
}
})
});
任何帮助表示赞赏!
我看了你的 HTML n JS,你能试试这个吗?
$('.alertform').each( function(){
var form = $(this);
form.validate({
基本上通过您的代码将所有 $(this) 更改为形式
这是关于 $(this) 的常见错误,有时它丢失了它的引用。
希望有所帮助
:)
完整的工作JS:
$('.alertform').each( function(){
var form = $(this);
form.validate({
rules: {
emailadres: {
required: true,
email: true
}
},
messages: {
emailadres: {
required: "Required",
minlength: "Fill it in",
email: "Not valid"
}
},
errorPlacement: function(error, element) {
element.nextAll('div').html(error);
},
success: function(label) {
label.addClass("valid").text("")
},
submitHandler: function() {
var email = form.find("input.email").val();
var productid = form.find("input.productid").val();
var dataString = 'email=' + email + '&productid=' + productid;
$.ajax({
type: "POST",
url: "/myurl.php",
data: dataString,
success: function(msg) {
if (msg==1) {
form.find(".email").attr("value", "");
form.find('.error').html("Thanks")
}
else {
form.find('.error').html("Something went wrong")
}
}
});
}
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.