views:

22

answers:

1

Hi!

My MySQL Database Provides A List of Items (and integer IDs with them) in a <select> and a qty field for usage on my web form (with style display: none so it is hidden). But: I want the user to be able to select how many choices of this type he wants to enter in the form - how can I dynamically make multiple selects?

Example: The products in the inventory are oranges, bananas and peaches. There is one select tag:

<select name="p[0]">
    <option value="2">Orange</option>
    <option value="23">Banana</option>
    <option value="31">Peach</option>
</select>
QTY <input type="text" name="qty[0]" />

Now I want to add another dropdown allowing the user to chose between ordering one, two or three classes of products. he could choose 2, and then two copies of the above code are inserted into the DOM so he can enter two product choices and quantities. (the Script would give them the names p[0] and p[1] etc.)

Can anyone help me here?

A: 

The simplest thing is to clone the nodes you already have as many times as needed (as opposed to creating new DOM via document.createElement() or innerHTML.

To start, surround your existing <select> and <input> with a div which has a well-known ID. Also, you want to add another DIV to put the repeated inputs into:

<div id="template">
  <select name="p[0]"> ... </select>
  QTY: <input name="qty[0]"/>
</div>
<div id="copies">
</div>

Now, create a function that will replicate the template some N number of times:

function makeCopies(num) {
  var template = document.getElementById('template');
  var output = document.getElementById('copies');

  // Delete existing nodes.
  output.innerHTML = '';

  // We start with 1, not 0, because we already have the template.
  for (var i = 1; i < num; i++) {
    var copy = template.cloneNode(true);
    // Change the input names according to index.
    copy.getElementsByTagName('select')[0].name = 'p[' + i + ']';
    copy.getElementsByTagName('input')[0].name = 'qty[' + i + ']';
    output.appendChild(copy);
  }   
}
levik