Reputation: 10141
I am using dropkick custom dropdown plugin to customize my select
elements and Parsley js
for form validation. On form validation, the error message does get displayed under the dropdown but error
class is not being added.
I know that dropkick
hides the <select>
and generates its own custom <div>
and <ul>
for displaying the custom dropdown. So is there a way to add error message class to these dynamically generated <div>
by dropkick?
Here is my code:
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>
Upvotes: 0
Views: 455
Reputation: 10141
Finally, found the solution: DEMO
Here is the code which I made and worked:
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();
}
}
});
Upvotes: 1