用javascript创建唯一的ID [英] create unique id with javascript
问题描述
我有一个表单,用户可以为多个城市添加多个选择框。问题是每个新生成的选择框都需要有唯一的ID。这可以是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 is JavaScript?
更新:这是选择城市的窗体的一部分。另请注意,当选择特定状态时,我正在使用一些php填充城市。
UPDATE: 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>
这是javascript:
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/>"
);
});
推荐答案
你不能只是保持一个运行的索引? p>
could you not just keep a running index?
var _selectIndex = 0;
...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
编辑
进一步考虑,您可能更喜欢使用阵列风格的名称来选择...
Upon further consideration, you may actually prefer to use array-style names for your selects...
例如
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
然后,在服务器端的php中,例如:
then, on the server side in php for example:
$cities = $_POST['city']; //array of option values from selects
编辑2 响应OP评论
可以使用DOM方法动态创建选项,如下所示:
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);
假设城市
数组已经存在
或者你可以使用innerHTML方法.....
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;
这篇关于用javascript创建唯一的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!