问题
I have a problem with select2 error placement when I save a form containing one or many select2.
Here is what I have: I have some Forms with some mandatory select2 inputs and they work fine showing the error with jQuery Validate but whatI want is the html to jump to the select2 with the error when I save the form. Currently the submit handler jumps just fine to any other element except the selectors.
回答1:
I ended up overwriting the invalid handler and call the id of the select2:
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
if($(validator.errorList[0].element).is(":visible"))
{
$('html, body').animate({
scrollTop: $(validator.errorList[0].element).offset().top
}, 100);
}
else
{
$('html, body').animate({
scrollTop: $("#s2id_" + $(validator.errorList[0].element).attr("id")).offset().top
}, 100);
}
}
}
回答2:
Use the same jQuery validator, simply move the error
$("#your_id").change(function(e) {
let id_error = `#${$(this).attr('id')}-error`
if(!$(this).valid()) {
$(id_error).detach().appendTo($('.select2-container').first())
}
})
来源:https://stackoverflow.com/questions/29172381/error-placement-select2