Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>could you not just keep a running index?</p> <pre><code>var _selectIndex = 0; ...code... var newSelectBox = document.createElement("select"); newSelectBox.setAttribute("id","select-"+_selectIndex++); </code></pre> <p><strong>EDIT</strong></p> <p>Upon further consideration, you may actually prefer to use array-style names for your selects...</p> <p>e.g.</p> <pre><code>&lt;select name="city[]"&gt;&lt;option ..../&gt;&lt;/select&gt; &lt;select name="city[]"&gt;&lt;option ..../&gt;&lt;/select&gt; &lt;select name="city[]"&gt;&lt;option ..../&gt;&lt;/select&gt; </code></pre> <p>then, on the server side in php for example:</p> <pre><code>$cities = $_POST['city']; //array of option values from selects </code></pre> <p><strong>EDIT 2</strong> In response to OP comment</p> <p>Dynamically creating options using DOM methods can be done as follows:</p> <pre><code>var newSelectBox = document.createElement("select"); newSelectBox.setAttribute("id","select-"+_selectIndex++); var city = null,city_opt=null; for (var i=0, len=cities.length; i&lt; len; i++) { city = cities[i]; var city_opt = document.createElement("option"); city_opt.setAttribute("value",city); city_opt.appendChild(document.createTextNode(city)); newSelectBox.appendChild(city_opt); } document.getElementById("example_element").appendChild(newSelectBox); </code></pre> <p>assuming that the <code>cities</code> array already exists</p> <p>Alternatively you could use the innerHTML method.....</p> <pre><code>var newSelectBox = document.createElement("select"); newSelectBox.setAttribute("id","select-"+_selectIndex++); document.getElementById("example_element").appendChild(newSelectBox); var city = null,htmlStr=""; for (var i=0, len=cities.length; i&lt; len; i++) { city = cities[i]; htmlStr += "&lt;option value='" + city + "'&gt;" + city + "&lt;/option&gt;"; } newSelectBox.innerHTML = htmlStr; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload