【问题标题】:In Javascript how do I add a new option into Html Select so inserted based on alphabetical value of text在Javascript中,如何根据文本的字母值将新选项添加​​到Html Select中
【发布时间】:2018-08-03 10:22:04
【问题描述】:

在 Javascript 中,如何根据文本的字母值将新选项添加​​到 Html Select 中?

所以我有这个

var selectMask = document.getElementById("filenamemasks");
var newmask = document.createElement("option");
newmask.text  = maskName;
newmask.value = maskMask;
selectMask.add(newmask);

但我希望它添加新掩码,因此它就在具有文本值的选项之后,它的值只是按字母顺序排列。

【问题讨论】:

标签: javascript html select


【解决方案1】:

您必须获取所有选项并将主题添加到名为options 的数组变量中。第二次将新项目添加到options 数组并对该数组进行排序并清除选择标签,最后添加已排序的options 以像这样选择标签。

      
document.getElementById('button').addEventListener('click',function(event){
        var options = [];
        var selectMask = document.getElementById("filenamemasks");
        var newmask = document.createElement("option");
        newmask.text  = document.getElementById('option_title').value;
        newmask.value = document.getElementById('option_value').value;
        options.push(newmask)
        var i;
        var txt;
        for (i = 0; i < selectMask.length; i++) {
        	options.push(selectMask.options[i]);
            txt = txt + "\n" + selectMask.options[i].text;
        }
        options.sort(function(a, b) {
            var textA = a.text.toUpperCase();
            var textB = b.text.toUpperCase();
            return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
        });
        
        selectMask.innerHtml="";
        for (i = 0; i < options.length; i++) {
            selectMask.add(options[i]);
        }
      });
        <select id="filenamemasks">
        <option value="1">Apple</option>
        <option value="2">Banana</option>
        <option value="3">Mango</option>
        <option value="4">Orange</option>
    </select>
    <input id="option_title" placeholder="title">
    <input id="option_value" placeholder="value">
    <button id="button">add item</button>

【讨论】:

【解决方案2】:

因此,基于 Mohammads 的答案以及我与我发现有效的解决方案相关联的答案只是为了

将新元素添加到列表末尾 ,然后将列表排序如下:

sortAlphabetically("#filenamemasks");

function sortAlphabetically(selectName) {
     var functionsToSort = $(selectName + ' ' + 'option');
     functionsToSort.sort(function(a,b){
        var textA = a.text.toUpperCase();
        var textB = b.text.toUpperCase();
        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
     });
     $(selectName).html(functionsToSort); 
}

【讨论】:

  • 您的答案较短,但您用 Javascript 说。我以为你不想使用任何第三方库。但它很棒。
猜你喜欢
  • 2018-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 2021-10-10
  • 1970-01-01
相关资源
最近更新 更多