简体   繁体   English

将动态创建的表单元素添加到jquery.validate?

[英]Add dynamically created form elements to jquery.validate?

My question seems to be the same as javascript validation for dynamic element , however the answers presented there do not appear to be working for me. 我的问题似乎与针对动态元素的javascript验证相同,但是那里给出的答案似乎对我没有用。 I am using the query.validate plugin, and it works fine for most of my form. 我正在使用query.validate插件,并且对于我的大多数表单都可以正常工作。 However, I have a button to add a row to a table containing several input elements. 但是,我有一个按钮可以向包含多个输入元素的表中添加一行。 The code I am using to add the form input elements is the following: 我用来添加表单输入元素的代码如下:

var table=document.getElementById('flightlegs');
var rowCount=table.rows.length-1;
var row=table.insertRow(rowCount);
...
var cell4=row.insertCell(3);
var element4=document.createElement("input");
element4.type="text";
element4.size="3";
element4.setAttribute("required", "required");
element4.maxlength="3";
element4.name="legto";
element4.id="legto"+rowCount;
cell4.appendChild(element4);
$('#legto'+rowCount).rules('add', {required:true});
...(more of the same for other cells)...

Ok, so this may not be the best way (i'm new at javascript), but it does add the input fields as desired. 好的,所以这可能不是最好的方法(我是javascript的新手),但是它确实会根据需要添加输入字段。 However, when hitting submit, those new fields are not included in the validation. 但是,单击“提交”时,这些新字段将不包括在验证中。 What am I missing here? 我在这里想念什么?

jquery.validate "selects only the first element for each name and only those with rules specified" (take a look at the source code of the plugin, the function called elements defined around line# 450). jquery.validate“仅为每个名称选择第一个元素,并且仅选择具有指定规则的元素 ”(查看插件的源代码,该函数称为在第450行定义的elements )。

In your case, each newly added form element has the name legto , which would cause jquery.validate to select only the first form element with that name and discard the rest wrt form validation. 在您的情况下,每个新添加的表单元素都具有名称legto ,这将导致jquery.validate仅选择具有该名称的第一个表单元素,并丢弃其余的表单验证。

Here's how you can fix this 这是解决此问题的方法

element4.name="legto"+rowCount;

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

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