0

In Javascript how do I add a new option into Html Select so inserted based on alphabetical value of text ?

So I have this

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

but I want it to add newmask so it comes just after the the option that has value of text just alphabetically before.

Paul Taylor
  • 13,411
  • 42
  • 184
  • 351

2 Answers2

2

You have to get all options and add theme to and array variable called options. Second add new item to options array and the sort that array and clear select tag and at the end add sorted options to select tag like this.

      
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>
Mohammad Rajabloo
  • 2,567
  • 19
  • 20
0

So building on Mohammads answer and the answer I linked to the solution I found that worked was just to

Add the new element to the end of the list ,then sort list as follows:

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); 
}
Paul Taylor
  • 13,411
  • 42
  • 184
  • 351