Reputation: 1948
I want to add the selected items in a drop down box and put them in a text box. I can now select just one item & put it in the text box :
Html code:
<select name="ncontacts" id = "contacts" multiple="yes" onclick="ChooseContact(this)"> </select>
JS code:
function ChooseContact(data)
{
document.getElementById ("friendName").value = data.value;
}
But when I select 2 items just the first one is written in the textbox. So, do you know how can I fix it, to let both of them appear in the textbox?
Upvotes: 2
Views: 490
Reputation: 2101
One possible (basic) solution is something like this:
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;
}
}
}
Upvotes: 2
Reputation: 17666
Another possible solution is:
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(', ');
}
edit: for the record -
Array.prototype
is slightly faster than []
in execution. But they do the same thing :) The performance penalty is not that much (I use []
in my code. but I may as well show you the slightly faster more verbose way).
Upvotes: 3
Reputation: 8306
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);
}
Upvotes: 2