Cory House
Cory House

Reputation: 15045

How do you structure an infinitely scalable form using Javascript?

I have a product registration form that allows the user to add additional product fields by clicking "add product". When the user clicks add product, Javascript creates new product field in an existing div.

I currently allow up to 10 products to be added on the form, so I setup a div structure like this:

<div id="product1"></div>
<div id="product2"></div>
<div id="product3"></div> etc...

I have one empty div for each product box that may be added by the user. I use Javascript's innerHTML method to populate the divs.

On to my question: How can I allow an unlimited number of products to be added at once? Obviously, my current setup won't support this since I need to hard code separate div's for each potential product so Javascript has a specific place to drop more data.

NOTE: Before someone suggests using a single div and appending new data into it, that doesn't work. Sadly, all data entered in previous fields is cleared whenever another field is added to the div by appending data like this:

document.getElementById('product').innerHTML += <input name="product"> 

Upvotes: 0

Views: 305

Answers (2)

Jay
Jay

Reputation: 833

I have one word to say jQuery :)

Example (to construct inputs on the fly for your form):

output = '';
for(i in products){
   output += '<div id="product_' + products[i].id + '">';
   output += '<input type="text" name="products[' + products[i].id + '][name]">';
   output += '<input type="text" name="products[' + products[i].id + '][price]">';
   output += '</div>';
}
$('#products_list').append(output);

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

You can dynamically add more DIVs easily. I use Prototype:

$("someContainerDiv").insert(new Element("div", { id: "product_"+prodId, 'class':'prod' }))

Then put your contents in $("product_"+prodId).innerHTML.

Upvotes: 4

Related Questions