开发者

jQuery Validation, multiple form ids for same function

开发者 https://www.devze.com 2022-12-24 16:14 出处:网络
Hi have two forms with the exact same validation rules, but different ids that I\'d like to combine into just one function.How can I do that?

Hi have two forms with the exact same validation rules, but different ids that I'd like to combine into just one function. How can I do that?

var validator = $("#ValidateForm1").validate({
errorPlacement: function(error, element) {
    if ( element.is(":radio") )
    开发者_如何转开发    error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
}       
});

var validator = $("#validateForm2").validate({
errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
}       
}); 


If you don't need the validator variable (which you're re-defining, so it appears you don't), just use a multiple selector:

$("#validateForm1, #validateForm2").validate({
  errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
  }       
});

Or, if you have a lot of forms like this, just give them a class and like this:

<form id="validateForm1" class="myFormClass"></form>
<form id="validateForm2" class="myFormClass"></form>
....
<form id="validateFormX" class="myFormClass"></form>

And a selector like this:

$(".myFormClass").validate({


Make the formId as a variable

var myFormId = "ValidateForm1"; // e.g. get the form id by using javascript

....

var validator = $("#"+ myFormId).validate({
errorPlacement: function(error, element) {
    if ( element.is(":radio") )
        error.appendTo( element.parent().next().next() );
    else if ( element.is(":checkbox") )
        error.appendTo ( element.next() );
    else
        error.appendTo( element.parent().next() );
}       
}); 
0

精彩评论

暂无评论...
验证码 换一张
取 消