我正在使用 dropkick 自定义下拉列表来自定义我的select
元素和 Parsley js
以进行表单验证。在表单验证时,错误消息确实显示在下拉列表中,但未添加error
类。
我知道dropkick
会隐藏<select>
并生成自己的自定义<div>
和<ul>
以显示自定义下拉列表。那么有没有办法通过dropkick为这些动态生成的<div>
添加错误消息类?
这是我的代码:
HTML:
<form class="form-inline row" id="quote_form_header">
<select class="dropkick_select"
data-parsley-required="true"
data-parsley-required-message="State is required.">
<option selected disabled>State</option>
<option>State1</option>
<option>State2</option>
</select>
<button type="submit">GET A QUOTE</button>
</form>
JS:
<script>
$(function(){
//Initialize dropkick on the form select elements
$(".dropkick_select").dropkick();
//Parsley js validation code
var parsley_valiation_options = {
errorTemplate: '<span class="error-msg"></span>',
errorClass: 'error',
}
if ($('#quote_form_header').length > 0)
$('#quote_form_header').parsley(parsley_valiation_options);
})
</script>
答案 0 :(得分:1)
最后,找到了解决方案: DEMO
以下是我制作和制作的代码:
var parsley_valiation_options = {
errorTemplate: '<span class="error-msg"></span>',
errorClass: 'error'
}
$('form').parsley(parsley_valiation_options)
window.Parsley.on('field:error', function() {
var element = $(this.$element);
// This global callback will be called for any field that fails validation.
//console.log('Validation failed for: ', this.$element);
//If the select element is a dropkick select, then add error class to dropkick generated custom <div> element
if ($(this.$element).hasClass('dropkick_select')) {
//var el = $(element).siblings('div.dk-select').first();
$('.dk-selected').addClass('error');
}
});
//Initialize dropkick on the form select elements
$(".dropkick_select").dropkick({
change: function() {
var select_elem = this.data.elem;
var selected_value = this.value;
//console.log("selected_value = "+selected_value);
//if selected value is not blank and if validation error message is currently being displayed under the select element, then remove the error message
if (selected_value != "" && $(select_elem).siblings('ul.parsley-errors-list').length > 0) {
$(select_elem).siblings('ul.parsley-errors-list').children('span').remove();
}
}
});