【问题标题】:get the multiple selection as comma separated from select box into a text input将多重选择作为逗号从选择框分隔到文本输入中
【发布时间】:2015-03-20 01:56:59
【问题描述】:

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

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

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

但是我无法实现。

我需要的是例如在选择这 2 个并提交后将 Australia,England 打印到文本输入中。

小提琴链接是:

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 +', ';   
}

【问题讨论】:

  • 可以调用JS代码吗?

标签: javascript html textinput multiple-select


【解决方案1】:

你可以这样做:

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

【讨论】:

    【解决方案2】:
    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(', ');
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多