javascripthtmlselectdynamic

How can I create unique IDs with JavaScript?


I have a form where a user can add multiple select boxes for multiple cities. The problem is that each newly generated select box needs to have a unique id. Can this be done in JavaScript?

Here is the part of the form for selecting cities. Also note that I'm using some PHP to fill in the cities when a specific state is selected.

<form id="form" name="form" method="post" action="citySelect.php">
<select id="state" name="state" onchange="getCity()">
    <option></option>
    <option value="1">cali</option>
    <option value="2">arizona</option>
    <option value="3">texas</option>
</select>
<select id="city" name="city" style="width:100px">
    
</select>

    <br/>
</form>

Here is the JavaScript:

$("#bt").click(function() {

$("#form").append(
       "<select id='state' name='state' onchange='getCity()'>
           <option></option>
           <option value='1'>cali</option>
           <option value='2'>arizona</option>
           <option value='3'>texas</option>
        </select>
        <select id='city' name='city' style='width:100px'></select><br/>"
     );
});

Solution

  • could you not just keep a running index?

    var _selectIndex = 0;
    
    ...code...
    var newSelectBox = document.createElement("select");
    newSelectBox.setAttribute("id","select-"+_selectIndex++);
    

    EDIT

    Upon further consideration, you may actually prefer to use array-style names for your selects...

    e.g.

    <select name="city[]"><option ..../></select>
    <select name="city[]"><option ..../></select>
    <select name="city[]"><option ..../></select>
    

    then, on the server side in php for example:

    $cities = $_POST['city']; //array of option values from selects
    

    EDIT 2 In response to OP comment

    Dynamically creating options using DOM methods can be done as follows:

    var newSelectBox = document.createElement("select");
    newSelectBox.setAttribute("id","select-"+_selectIndex++);
    
    var city = null,city_opt=null;
    for (var i=0, len=cities.length; i< 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);
    

    assuming that the cities array already exists

    Alternatively you could use the innerHTML method.....

    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< len; i++) {
        city = cities[i];
        htmlStr += "<option value='" + city + "'>" + city + "</option>";
    }
    newSelectBox.innerHTML = htmlStr;