Bootstrap 3 + Chosen + jquery validate loses forma

2019-07-03 04:19发布

问题:

I have the code below http://jsfiddle.net/emamut/CBjmj/4/

$.validator.setDefaults({ ignore: ":hidden:not(select)" });
$('form').validate({
    highlight: function(element) {
        $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else {
            error.insertAfter(element);
        }
    }
});

but when select validate the formatting is lost and returns the normal format of Chosen

回答1:

In the errorPlacement option, when you use insertAfter it inserts the error message between the select element and the div.chosen-container. This fouls up the CSS used for the chosen widget. For example, if you use insertBefore, the problem goes away:

$.validator.setDefaults({ ignore: ":hidden:not(select)" });
    $('form').validate({
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.form-group').removeClass('has-error');
    },
    errorElement: 'span',
    errorClass: 'help-block',
    errorPlacement: function(error, element) {
        if(element.parent('.input-group').length) {
            error.insertAfter(element.parent());
        } else if (element.is('select')) {
            error.insertBefore(element);
        } else
        {
            error.insertAfter(element);
        }
    }
});


回答2:

If what you want is to add the error message bellow the chosen, you always can add it after adding this clause to the errorPlacement:

else if (element.is('select')) {
   error.insertAfter(element.siblings(".chosen-container"));
}

I've forked your fiddle: http://jsfiddle.net/alfupe/0Lwgmmav/