2016-05-31 63 views
1

不錯選擇使用jQuery驗證? 因爲我得到一個奇怪的錯誤,我會試着解釋它jQuery驗證和尼斯選擇一致?

  • ,但仍未提交了表格,我能夠從好的選擇插件選擇的值,並將其更新正確的(默認選擇下拉)值,我可以提交表格沒有問題

  • 現在,如果我刷新頁面,然後我提交表單,jQuery錯誤驗證追加按預期,因爲我沒有選擇一些值,所以我選擇了一些值從(不錯的選擇值),現在它不更新(默認選擇)值,所以我不能提交表格

我認爲,當驗證插件被稱爲好的選擇不是動態更新的,也許我錯過了一些東西

FIDDLE

HTML

<form id="MyForm"> 
    <select id="MySelect" name="select"> 
    <option value="">Select a value</option> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
    <option value="4">4</option> 
    </select> 
    <button id="MyButton" type="submit">Submit</button> 
</form> 

jQuery的

$(document).ready(function() { 
    // Form Validate 
    $('#MyForm').validate({ 
     ignore: [], 
     rules: { 
      select: { 
       selectcheck: true 
      } 
     } 
    }); 

    jQuery.validator.addMethod('selectcheck', function (value) { 
     return (value != ''); 
    }, "Value required"); 

    // Activate NiceSelect 
    $('#MySelect').niceSelect(); 
}); 

任何幫助,將不勝感激提前

感謝

回答

1

jQuery Validate plugin aut或者在select元素之後插入驗證消息。但是,在您的情況下,元素在動態創建Nice Select div時隱藏;驗證插件不能再看到或切換此label

使用the errorPlacement function將驗證消息置於之後的Nice Select div元素。我的自定義功能是通用的,適用於窗體中所有隱藏的select元素。

errorPlacement: function(error, element) { 
    if (element.is('select:hidden')) { 
     error.insertAfter(element.next('.nice-select')); 
    } else { 
     error.insertAfter(element); 
    }   
} 

但是,這個答案還沒有完成。 jQuery Validate插件通常基於用戶與select元素進行交互來觸發驗證。由於您的select元素處於隱藏狀態,並且用戶沒有直接與其交互,因此只要Nice Select元素髮生更改,就不會觸發驗證。

使用自定義change處理函數,以確保無論何時尼斯選擇元素被改變的確認消息更新中...

$('#MySelect').on('change', function() { 
    $(this).valid(); 
}); 

工作演示:https://jsfiddle.net/9yvz4ztv/


BTW:您無需編寫自定義規則以確保select元素包含值。只需使用required規則。

rules: { 
    select: { 
     required: true 
    } 
} 
1

這是因爲error標籤位置。
的標籤貼在<select>元素之後直接放置,但插件使用此代碼觸發<select>的變化:

// .prev() in this case is the <label class="error">, not "select" ... 
n.prev("select").val(s.data("value")).trigger("change") 

您可以更改標籤的位置,用errorPlacement選項:

$('#MyForm').validate({ 
    ignore: [], 
    rules: { 
    select: { 
     selectcheck: true 
    } 
    }, 
    errorPlacement: function(error, element) { 
    if (element.attr("name") == "select") { 
     // place the label after the .nice-select DIV, not <select>: 
     error.insertAfter(".nice-select"); 
    } else { 
     error.insertAfter(element); 
    } 
    } 
}); 

JSFiddle demo