Adding options to select with javascript

Asked
Active3 hr before
Viewed126 times

8 Answers

optionsaddingselect
90%

document.getElementById().,Software Recommendations, Does determinism prevent rationality? , Podcast 378: The paranoid style in application development

You could achieve this with a simple for loop:

var min = 12,
   max = 100,
   select = document.getElementById('selectElementId');

for (var i = min; i <= max; i++) {
   var opt = document.createElement('option');
   opt.value = i;
   opt.innerHTML = i;
   select.appendChild(opt);
}

[How] do [I] apply this to more than one element?

function populateSelect(target, min, max) {
   if (!target) {
      return false;
   } else {
      var min = min || 0,
         max = max || min + 100;

      select = document.getElementById(target);

      for (var i = min; i <= max; i++) {
         var opt = document.createElement('option');
         opt.value = i;
         opt.innerHTML = i;
         select.appendChild(opt);
      }
   }
}
// calling the function with all three values:
populateSelect('selectElementId', 12, 100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

And, finally (after quite a delay...), an approach extending the prototype of the HTMLSelectElement in order to chain the populate() function, as a method, to the DOM node:

HTMLSelectElement.prototype.populate = function(opts) {
   var settings = {};

   settings.min = 0;
   settings.max = settings.min + 100;

   for (var userOpt in opts) {
      if (opts.hasOwnProperty(userOpt)) {
         settings[userOpt] = opts[userOpt];
      }
   }

   for (var i = settings.min; i <= settings.max; i++) {
      this.appendChild(new Option(i, i));
   }
};

document.getElementById('selectElementId').populate({
   'min': 12,
   'max': 40
});
load more v
88%

Second, add the option to the select box.,Otherwise, we create a new option and add it to the selection box.,Second, add the new option to the select box using the appendChild() method:,First, construct a new option using DOM methods:

First, use the Option constructor to create a new option with the specified option text and value:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
let newOption = new Option('Option Text', 'Option Value');
Code language: JavaScript(javascript)
load more v
72%

The HTMLSelectElement.add() method adds an element to the collection of option elements for this select element. , before is optional and an element of the collection, or an index of type long, representing the item should be inserted before. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection. ,Thrown if the item passed to the method is an ancestor of theHTMLSelectElement.,PropertiesautofocusdisabledformlabelsoptionsselectedIndexselectedOptionstype

collection.add(item[, before]);
load more v
65%

An option can be added to a select element using 3 approaches in jQuery:,The Option() constructor is used to create a new option element. A new option is created with the text and the value of the option as the parameters. This element is then added to the select box with the append() method.,Method 1: Append the option tag to the select box,The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.

Syntax:

$('#selectBox').append(`${optionText}`)

Syntax:

$('#selectBox').append(new Option(optionText, optionValue))

Syntax:

$('#selectBox').append($('<option>').val(optionValue).text(optionText))
load more v
75%

This Javascript post was going to be about language selection in FCKEditor from a drop down box as a follow up to the previous FCKEditor post but I’ve decided to postphone that post until Friday and look at how to add options to an HTML <select> drop down box with Javascript, because the next FCKEditor post will be doing just that.,Friday’s post will look at how to add a language selection drop down box in FCKEditor, using the way of populating a select drop down box with Javascript from an array as shown in this post.,To add a new option to it, with the text “Text 1” displaying in the drop down box, and the value “Value1” being what would be submitted from the form, do this:,To do a window.alert to show the current text and value of the selected option do this:

<select id="example-select"></select>
load more v
40%

javascript add option / element to select:
   const newOpt = document.getElementById('option-input');
let mySelect = document.getElementById('mySelect'); //Object not array
const opts = Object.values(mySelect.options);
const option = document.createElement('option');
optValues = opts.map(opt => opt.value.toLowerCase());
//Validate if option exists
if (optValues.indexOf(newOpt.value.toLowerCase()) !== -1) {
   newOpt.nextElementSibling.after("Category exists");
} else {
   option.value = newOpt.value;
   option.text = newOpt.value;
   mySelect.add(option);
   mySelect.value = option.value;
}
22%

There is no reason to use document.createElement for adding options when JavaScript actually has a built in function that adds the entire option tag with value and text all in one go,I just saw an example of a select box where you could add an option by typing an not existing option in the select box it self and by clicking a submit button it was added to the database as well. I saw many examples where you could add an option by declaring a new option in in a function:,Of course as a combobox there’d be nothing to stop someone typing ‘One’ in the field regardless of how you define the options.,Here’s the combobox that you’re looking for. Enable the remote database option and you’re all good to go.

I just saw an example of a select box where you could add an option by typing an not existing option in the select box it self and by clicking a submit button it was added to the database as well. I saw many examples where you could add an option by declaring a new option in in a function:

function myFunction() {
   var x = document.getElementById("mySelect");
   var option = document.createElement("option");
   option.text = "Kiwi";
   x.add(option);
}
load more v
60%

The first method is appending the option tag to the select box. The option tag is created like an HTML string, and the select box is selected with the jQuery selector. The option is added with the append() method. This method inserts the specified content as the last child of the jQuery collection, thus adding the option to the select element.,The third method is creating a new jQuery DOM element with the option tag. The value of the tag is specified with the val() method and the text with thetext() method. Here, also you should use the append() method to add the element to the select box.,In this tutorial, we will find out the best method for adding options to a select element from a JavaScript object using jQuery. Let’s discuss each of the methods and try to solve the problem together.,The second method uses the Option() constructor for creating a new option. The Option() constructor is used to create a new option element. For creating a new option, the text and the value parameters are used. Then, the element is appended to the select box with the append() method:

<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js">
    </script>
  </head>
  <body>
    <p>
      Select one of the proposed options:
      <select id="selectId">
        <option value="firstEl">First Element</option>
        <option value="secondEl">Second Element</option>
      </select>
    </p>
    <button onclick="addOption()">
      Add Element
    </button>
    <script type="text/javascript">
      function addOption() {
        optText = 'New elemenet';
        optValue = 'newElement';
        $('#selectId').append(`<option value="${optValue}">${optText}</option>`);
      }
    </script>
  </body>
</html>
load more v