简体   繁体   English

jQuery验证动态表单输入上的插件不起作用

[英]jquery validate plugin on dynamic form inputs not working

I've a form where I'm having some fields and then if needed user can add more fields of same type. 我有一个表格,其中有一些字段,然后如果需要,用户可以添加更多相同类型的字段。 Im using http://jqueryvalidation.org/ validate plugin to validate fields. 我正在使用http://jqueryvalidation.org/ validate插件来验证字段。

As I read somewhere jquery validate plugin requires unique names to fields for validating them. 当我在某处阅读jquery validate插件时,需要使用唯一的名称来验证字段。 So i'm naming each field uniquely. 所以我要对每个字段进行唯一命名。 First I hoped that validate plugin will take care of dynamically added element's validation if I add rules using classes. 首先,我希望如果我使用类添加规则,则validate插件将负责动态添加元素的验证。 But it turns out it does not. 但事实并非如此。

So even if name of each field is unique, validate plugin validates only first input which was rendered initially. 因此,即使每个字段的名称都是唯一的,validate插件也仅验证最初呈现的第一个输入。

I even tried using $.clone() in hope that it'll take care of all event bindings. 我什至尝试使用$ .clone()希望它能处理所有事件绑定。 But it did not worked for me. 但这对我没有用。 So I moved to underscore to repeat the markup as there are number of fields and I don't want to write templates in JS and name accordingly. 所以我移至下划线以重复标记,因为字段数量众多,并且我不想用JS编写模板并相应地命名。

I can't find a solution to this and stuck here. 我找不到解决方案,只能停留在这里。 Can't more on until this issue is resolved. 在此问题解决之前无法继续。

Here's JS that I've written. 这是我写的JS。

$("#work_form").validate();

$(".work_emp_name").rules("add", {
    required: true
});

_.templateSettings.variable = "element";
var tpl = _.template($("#form_tpl").html());

var counter = 1;

$("form").on("click", ".add_employer", function (e) {
    e.preventDefault();
    var tplData = {
        i: counter
    };
    $("#word_exp_area").append(tpl(tplData));
    counter += 1;
});

Please find markup in fiddle set up. 请在小提琴设置中找到标记。

example and code set up here 示例和代码在这里设置

When using one of the methods from this plugin, like .rules() , and targeting more than one element, like a class , you must also use the jQuery .each() method. 使用此插件中的一种方法.rules().rules()并针对多个元素(如class .rules()定位时,还必须使用jQuery .each()方法。

$('.work_emp_name').each(function () {
    $(this).rules("add", {
        required: true
    });
});

And you cannot use .rules() on elements that don't yet exist in the DOM. 而且,您不能在DOM中尚不存在的元素上使用.rules() Simply move the .rules() method to inside the function that creates your new inputs. 只需将.rules()方法移至创建新输入的函数中。

$("form").on("click", ".add_employer", function (e) {
    e.preventDefault();
    var tplData = {
        i: counter
    };
    $("#word_exp_area").append(tpl(tplData));
    counter += 1;
    $('.work_emp_name').each(function () { 
        $(this).rules("add", {
            required: true
        });
    });
});

Working DEMO: http://jsfiddle.net/Yy2gB/10/ 工作演示: http : //jsfiddle.net/Yy2gB/10/


However, you can make it more efficient by only targeting the one new field , instead of all fields with the work_emp_name class . 但是,您可以通过仅定位一个新字段而不是使用work_emp_name class的所有字段来提高work_emp_name

$("form").on("click", ".add_employer", function (e) {
    e.preventDefault();
    var tplData = {
        i: counter
    };
    $("#word_exp_area").append(tpl(tplData));   // <- add new field
    $('input[name="work_emp_name['+counter+']"]').rules("add", {  // <- apply rule to new field
        required: true
    });
    counter += 1;
});

Working DEMO: http://jsfiddle.net/Yy2gB/11/ 工作演示: http//jsfiddle.net/Yy2gB/11/


Both of my examples above are for adding rules to the dynamically created fields. 我上面的两个示例都是将规则添加到动态创建的字段中。 You'll still need to declare any rules for your static fields upon dom ready as follows... 您仍然需要在dom准备就绪时为静态字段声明任何规则,如下所示...

$("#work_form").validate({
    rules: {
        "work_emp_name[0]": {
            required: true
        }
    }
});

Returns the validations rules for the first selected element or Adds the specified rules and returns all rules for the first matched element. 返回第一个选定元素的验证规则,或者添加指定的规则并返回第一个匹配元素的所有规则。 Requires that the parent form is validated, that is, $( “form” ).validate() is called first or 要求验证父表单,即首先调用$(“ form”).validate()或

Removes the specified rules and returns all rules for the first matched element. 删除指定的规则并返回第一个匹配元素的所有规则。 more info 更多信息

function addRule(id){
    $("[name='work_emp_name["+id+"]']").rules("add", {
        required: true
    });
}
$("#work_form").validate();
addRule(0);

_.templateSettings.variable = "element";
var tpl = _.template($("#form_tpl").html());

var counter = 1;

$("form").on("click", ".add_employer", function (e) {
    e.preventDefault();
    var tplData = {
        i: counter
    };
    $("#word_exp_area").append(tpl(tplData));
    addRule(counter);
    counter += 1;
}); here

That's because jQuery Validation only validates the first occurrence of the array currently. 这是因为jQuery Validation仅验证当前第一次出现的数组。

You can check my commit on the plugin that will just work fine on any occurrence of the named array. 您可以在插件上检查我的提交 ,该提交在任何命名数组的情况下都可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM