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

时间:2022-11-24 08:40:49

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. 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. But it turns out it does not.

当我在某处阅读时,jquery validate插件需要用于验证字段的唯一名称。所以我将每个字段唯一命名。首先,我希望如果我使用类添加规则,validate插件将负责动态添加元素的验证。但事实证明它没有。

So even if name of each field is unique, validate plugin validates only first input which was rendered initially.

因此,即使每个字段的名称都是唯一的,验证插件也只验证最初呈现的第一个输入。

I even tried using $.clone() in hope that it'll take care of all event bindings. 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.

我甚至尝试使用$ .clone(),希望它能处理所有事件绑定。但它对我没有用。所以我转向下划线重复标记,因为有多个字段,我不想在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

示例和代码在此处设置

3 个解决方案

#1


35  

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())并且定位多个元素(如类)时,还必须使用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. Simply move the .rules() method to inside the function that creates your new inputs.

并且您不能在DOM中尚不存在的元素上使用.rules()。只需将.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类的所有字段来提高效率。

$("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
        }
    }
});

#2


3  

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

#3


1  

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.

您可以在插件上检查我的提交,它将在任何出现的命名数组上正常工作。

#1


35  

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())并且定位多个元素(如类)时,还必须使用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. Simply move the .rules() method to inside the function that creates your new inputs.

并且您不能在DOM中尚不存在的元素上使用.rules()。只需将.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类的所有字段来提高效率。

$("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
        }
    }
});

#2


3  

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

#3


1  

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.

您可以在插件上检查我的提交,它将在任何出现的命名数组上正常工作。