将多个 selection 作为逗号从 select 框分隔到文本输入中

get the multiple selection as comma separated from select box into a text input

我不懂js。我需要将多个 selection 作为逗号从 select 框分隔到文本输入中。

with pure js,我发现只有这个问题与SO有关。 Multiple selections into input box

然后我试了那个问题的js代码。 (问题 js 组合与接受的答案)

然而我无法实现。

我需要的是例如在 selecting 那些 2 并提交后将 Australia,England 打印到文本输入中。

Fiddle link 是:

http://jsfiddle.net/0k2m7gLo/

代码在 FIDDLE

HTML

<form>
    <select id="countries" multiple>
      <option value="val0">Australia</option>
      <option value="val1">England</option>
      <option value="val2">France</option>
    </select>
    <input type="button" value="Show Index" onclick="showSelected();" />
</form>
<p>selected countries by comma seperated</p>
<form><input type="text" id="txtText" /></form>

不成功的 JS

function showSelected()
{
    var selObj = document.getElementById('countries');
  var txtTextObj = document.getElementById('txtText');

  var selIndex = selObj.selectedIndex;
 txtTextObj.value += selObj.options[selIndex].text +', ';   
}

你可以这样做:

var selObj = document.getElementById('countries'),
    txtTextObj = document.getElementById('txtText'),
    selected = [];

for(var i = 0, l = selObj.options.length; i < l; i++){
    //Check if the option is selected
    if(selObj.options[i].selected){
        selected.push(selObj.options[i].textContent);
    }
} 
txtTextObj.value = selected.join(', ');

jsFiddle

function updateSelected() {
  var select = document.getElementById('countries'),
      options = select.options,
      input = document.getElementById('selected');

  var selected = [];

  for (var i = 0, ii = options.length; i < ii; ++i) {
    var opt = options[i];

    if (opt.selected) {
      selected.push(opt.innerHTML);
    }
  }

  input.value = selected.join(', ');
}