[英]Select many items from dropbox & let them appear in a text box
我想在下拉框中添加所选项目,然后将其放在文本框中。 我现在只能选择一项并将其放在文本框中:
Html代码:
<select name="ncontacts" id = "contacts" multiple="yes" onclick="ChooseContact(this)"> </select>
JS代码:
function ChooseContact(data)
{
document.getElementById ("friendName").value = data.value;
}
但是,当我选择2个项目时,只有第一个项目写在文本框中。 因此,您知道如何解决它,以使它们都出现在文本框中吗?
另一种可能的解决方案
function ChooseContact(list) {
var selected = [];
Array.prototype.forEach.call(list.options, function(option) {
if( option.selected ) {
selected.push(option.value);
}
});
document.getElementById('friends').value = selected.join(', ');
}
编辑:记录-
Array.prototype
在执行方面比[]
快一些。 但是它们却做同样的事情:)性能损失并没有那么多(我在代码中使用[]
。但我也可能会向您展示稍微更详细的方式)。
一种可能的(基本)解决方案是这样的:
function ChooseContacts(selectElem) {
var txtBox = document.getElementById ("friendName");
txtBox.value = '';
for (var i=0; i<selectElem.options.length; i++) {
if (selectElem.options[i].selected) {
txtBox.value += selectElem.options[i].value;
}
}
}
function chooseContact(fromElem, appendToElem, separator){
separator = separator|| " ";
var result = [];
[].forEach.call(fromElem.options, functon(option){
if(option.checked){
result.push(option.value);
}
});
appendToElem.value = result.join(separator);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.