我需要将所有下拉选择的项目复制到另一个下拉菜单。
我不知道为什么还要在每个城市名称后复制一个空格。 请告诉我为什么。
//var values;
// function to copy all the selected city name to //another drop box
function copy_city_name(city) {
var x = document.getElementById("new_list");
//copy array values to any another variable(city_list)
var city_list = city;
//document.write(city);
//ittration to copy all the name to another drop down
for (var i = 0; i <= city_list.length; i++) {
var opt = city_list[i];
var e1 = document.createElement("option");
e1.textContent = opt;
e1.value = opt;
//alert(e1);
//console.log(e1);
x.add(e1);
}
}
// function to select all the selected city name in a array.
function get_city_name() {
// body...
var fld = document.getElementById('city_name');
// ittration to get names of all the selected city name.
for (var i = 0; i < fld.options.length; i++) {
var values = [];
if (fld.options[i].selected) {
values.push(fld.options[i].value);
copy_city_name(values); // passed all values to function
}
}
}
<form>
<select multiple="multiple" name="city" id="city_name">
<option value="a">A</option>
<option value="b"> B </option>
<option value="c"> C</option>
<option value="d"> D</option>
</select>
<button type="button" onclick="get_city_name()">select multiple</button>
<select multiple="multiple" name="get" id="new_list">
</select>
</form>
答案 0 :(得分:1)
// function to copy all the selected city name to another select
function copy_city_name() {
var newList = document.getElementById("new_list"),
opts = document.querySelectorAll('#city_name option:checked');
// iteration to get names of all the selected city names.
for (var i = 0; i < opts.length; i++) {
var opt = document.createElement("option");
opt.textContent = opts[i].textContent;
opt.value = opts[i].value;
newList.add(opt);
}
}
<form>
<select multiple="multiple" name="city" id="city_name">
<option value="a">A</option>
<option value="b"> B </option>
<option value="c"> C</option>
<option value="d"> D</option>
</select>
<button type="button" onclick="copy_city_name()">select multiple</button>
<select multiple="multiple" name="get" id="new_list">
</select>
</form>
如果要移动它们,它甚至更短
for (var i = 0; i < opts.length; i++) {
newList.add(opts[i]);
}
答案 1 :(得分:-1)
在您的copy_city_name
函数循环中,它必须为i < city_list.length;
而不是i <= city_list.length;
然后将get_city_name
的{{1}}数组移出循环以收集所有选定的选项
values
function copy_city_name(cities) {
var list = document.getElementById("new_list");
for (var i = 0; i < cities.length; i++) {
var city = cities[i];
var option = document.createElement("option");
option.textContent = city;
option.value = city;
list.add(option);
}
}
function get_city_name() {
var fld = document.getElementById('city_name');
var values = [];
for (var i = 0; i < fld.options.length; i++) {
if (fld.options[i].selected) {
values.push(fld.options[i].value);
}
}
copy_city_name(values);
}