[英]jQuery tools validator, how to make it work with dynamically added elements?
我正在嘗試使用jQuery工具驗證程序來實現表單驗證。
我的表單並不簡單,它包含兩個步驟:
問題是驗證者似乎不知道要驗證的新輸入。 如何刷新它並使驗證器知道動態添加的輸入?
我試過了
form.data("validator").destroy();
form.validator();
但是沒有運氣。
有什么建議么?
我很想使用unbind函數( http://api.jquery.com/unbind/ )的功能解決問題。此解決方案的優點在於,我們不必將新添加的字段附加到驗證器手動對象。完整代碼如下:
/ * server-side.html文件* /
<html> <!-- This is a jQuery Tools standalone demo. Feel free to copy/paste. http://flowplayer.org/tools/demos/ Do *not* reference CSS files and images from flowplayer.org when in production Enjoy! --> <head> <title>jQuery Tools standalone demo</title> <!-- include the Tools --> <script src="http://cdn.jquerytools.org/1.2.6/full/jquery.tools.min.js"></script> <!-- standalone page styling (can be removed) --> <link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/css/standalone.css"/> <link rel="stylesheet" type="text/css" href="http://static.flowplayer.org/tools/demos/validator/css/form.css"/> </head> <body> <form id="myform"> <fieldset> <h3>Sample registration form</h3> <p> Enter bad values and then press the submit button. </p> <p> <label>website *</label> <input type="url" name="url" required="required" /> </p> <p> <label>name *</label> <input type="text" name="name" pattern="[a-zA-Z ]{5,}" maxlength="30" /> </p> <p> <label>age</label> <input type="number" name="age" size="4" min="5" max="50" /> </p> <p id="terms"> <label>I accept the terms</label> <input type="checkbox" required="required" /> </p> <button type="submit">Submit form</button> <button type="reset">Reset</button> </fieldset> </form> <script> // initialize validator and add a custom form submission logic var submitEvent = function(){$("#myform").validator().submit(function(e) { var form = $(this); // client-side validation OK. if (!e.isDefaultPrevented()) { // submit with AJAX $.getJSON("server-fail.js?" + form.serialize(), function(json) { // everything is ok. (server returned true) if (json['valid'] === 'true') { if($("#testField").length == 0){ $("#terms").before('<p> <label id="testField">email *</label><input type="email" name="email" required="required" /></p>'); } else { alert("new field validated successfully"); } form.unbind("submit"); submitEvent(); // server-side validation failed. use invalidate() to show errors } else { form.data("validator").invalidate(json); } }); // prevent default form submission logic e.preventDefault(); } });}; submitEvent(); </script> </body> </html>
/ * server-fail.js文件* /
{ "name": "Invalid name. Our apologies", "age": "You are too young", "valid": "true" }
您可以嘗試以下代碼以使功能更加動態。享受:)
好吧,正如我想的那樣,新元素未附加到現有的驗證器對象上。
因此,方法是為新創建的字段初始化驗證器,並連接表單的Submit事件以從代碼執行驗證:
var input = $("#newDiv :input").validator();
$("#formId").submit(function(e)
{
input.data("validator").checkValidity();
});
這很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.