How to add new options in select options using JavaScript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mahirinku
    New Member
    • Apr 2013
    • 1

    How to add new options in select options using JavaScript

    how to add new more options in select box options using JavaScript . Please tell me what i do for add more options in options box using JavaScript .
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Try

    Code:
    var newOption= document.createElement("OPTION");
    newOption.innerText = "yourText";
    newOption.value = "yourValue";
    document.yourForm.yourSelect.options.add(newOption);

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      That looks like a very IE-specific way of adding options.

      I would suggest a simple:
      Code:
      yourSelect.options[yourSelect.options.length] = new Option(text, value);
      If using the add method, you'd need a try/catch block to deal with IE's non-standard implementation (probably been fixed in newer versions, but I haven't checked).

      Comment

      • r035198x
        MVP
        • Sep 2006
        • 13225

        #4
        Not to mention that
        Code:
        options[yourSelect.options.length] = new Option(text, value);
        is much cleaner and simpler ...

        Comment

        • Sherin
          New Member
          • Jan 2020
          • 77

          #5
          Try This Code

          Code:
          var min = 10,
              max = 50,
              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);
          }

          Comment

          • mirandapalmer
            New Member
            • Feb 2021
            • 2

            #6
            I have the same problems. Thanks for share this.

            Comment

            Working...