简体   繁体   中英

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. I am using the query.validate plugin, and it works fine for most of my form. 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. 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).

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.

Here's how you can fix this

element4.name="legto"+rowCount;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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