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 on add a product, Javascript creates a new product field in the existing div.

I currently allow up to 10 products to be added to the form, so I set the 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 window that can be added by the user. I am using Javascript innerHTML method to fill a div.

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 as I need to hardcode a separate div for each potential product, so the Javascript has a specific place to drop more data.

NOTE. Before someone suggests using a single div and adding new data to it, it won't work. Unfortunately, all data entered in the previous fields is removed when another field is added to the div, adding data like this:

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

      

0


source to share


2 answers


You can add more DIVs dynamically. I am using Prototype :

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

      



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

.

+4


source


I have one word to say jQuery :)

Example (to create on-the-fly input 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);

      

0


source







All Articles