views:

180

answers:

2

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">
+4  A: 

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.

Diodeus
Ah! Great idea! Can I create another div by simply calling innerHTML to write a div inside an existing div? Would this insert a new div in the DOM? I'm not using a JS library on this project.
Cory House
Yes, you certainly can. :)
Diodeus
Be aware, browsers manipulate the markup entered directly into innerHTML.. therefore appending to innerHTML can sometimes result in unexpected results.Just alert innerHTML in IE and see what I mean :)
Jay
Excellent. Thanks for clarifying!
Cory House
A: 

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);
Jay
It's easy to say, but how about an example?
Diodeus