2017-05-04 51 views
0

添加錯誤類我使用dropkick定製下拉插件定製我select元素和Parsley js表單驗證。在表單驗證中,錯誤消息在下拉列表中顯示,但error類未被添加。香菜JS與踢反彈球表單驗證 - 無法自定義選擇下拉

我知道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> 

回答

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(); 
    } 
    } 
}); 
+0

看起來不錯。可以使用'field:success'來取代錯誤。 –