tags:

views:

435

answers:

1

I'm creating a form which dynamically inserts data entered into the form fields into the database as and when anything has been entered. I'm now working on adding dynamic rows to the form (ie. duplicating an existing row if the user needs to add extra information). I've run into two problems.

The code i'm using is based on the following:

function addFormField() {
$("#divTxt").append("<div id='education" + id + "'><input name='name' id='name' type='text' size='20'><a href='#' onClick='removeFormField(\"#education" + id + "\"); return false;'><img src='images/minus.gif' width='10px' border=0></img></a></div>");
}

Problem 1: The original line (before inserting the next) works fine but I can't seem to figure out why the new line isn't even attempting to send data via $.post using a input blur function. Is it because all the are having the same name or is it because the actual $.post code is loaded on document ready and is ignoring this as the form fields appear after a click event?

Problem 2: To insert the data from the newly added rows, would I need to use a jquery.each to loop through the form fields if they have the same name/id?

Well, any suggestions would be good at this point - its head scratching time!

+2  A: 

Don't use the same ID and name and you'll be headed in the right direction. It's not valid HTML to use the same ID.

Also, then when you goto post the data (whether it's with jQuery.serialize()) or just a standard POST, it will be a lot easier to process the info.

function addFormField() {
$("#divTxt").append("<div id='education" + id + "'><input name='name' id='name' type='text' size='20'><a href='#' onClick='removeFormField(\"#education" + id + "\"); return false;'><img src='images/minus.gif' width='10px' border=0></img></a></div>");
}

From looking at your code: you can use the DOM to refer to the field you would like to remove as well. Hopefully this removes the need for the ID that you had.

This looks like:

function addFormField(index) {
$("#divTxt").append("<div ><input name='name"+index+"' type='text' size='20'><a href='#' onClick='$(this.parentNode).remove()'><img src='images/minus.gif' width='10px' border=0></img></a></div>");
}
altCognito