Dynamically add drop down list

11,477

Solution 1

Replace createElement('input') with createElement('select') and then create additional option elements the same way: var opt1 = document.createElement('option') and Set the attributes (value that goes to the server and text that the user sees, usually) on each element. Then append each option object to your select object, and append the select object into the DOM as you are doing with your input object now.

Here's an example using an array of animals, and sending the first letter as the value to the server:

var items = ['aardvark', 'bear', 'cat', 'donkey'];
var values = ['a', 'b', 'c', 'd'];
var sel = document.createElement('select');
sel.setAttribute('name', 'item[]');
for (var i = 0; i < 4; i++) {
    var opt = document.createElement('option');
    opt.setAttribute('text', items[i]);
    opt.setAttribute('value', values[i]);
    sel.appendChild(opt);
}
// ... from here on, set any other attributes, like classes
// Then and add the select object to the DOM:
item.appendChild(sel);

Solution 2

Hi please try this code.

        <html>
    <body>

    <div id='item'></div>

    <input name='add' type='button' id='add' value='Add Item'/>

    </body>
    </html>

    <script type="text/javascript">
        var item = document.getElementById('item');

        var stopper=0;

        document.getElementById('add').onclick = function () {

        stopper=stopper+1;

         var select = document.createElement('select'),
              div = document.createElement('div');

          select.setAttribute("name", "item[]");
          select.setAttribute("class", "item");
            //this is just an example. You need to replace this code with ajax that is fetching 
//from the Database.. and please use jquery it makes your work easier.
            var  count = getRandomInt(1, 5);
            for(var a=1; a<=count; a++) {
                var option = document.createElement('option');
                 var t =  randon_val();
            //end
              option.setAttribute("value",t);
              option.appendChild(document.createTextNode(t));
                select.appendChild(option);
            }



          div.appendChild(select);
          item.appendChild(div);

        };

        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

        function randon_val()
        {
            var text = "";
            var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            for( var i=0; i < 5; i++ )
                text += possible.charAt(Math.floor(Math.random() * possible.length));

            return text;
        }
    </script>
Share:
11,477
Logan Wayne
Author by

Logan Wayne

If you are good at something, never do it for free. Unless you are in StackOverflow. Everything is free in StackOverflow. #SOreadytohelp

Updated on June 16, 2022

Comments

  • Logan Wayne
    Logan Wayne almost 2 years

    I can dynamically add text boxes like this:

    <html>
    <body>
    
    <div id='item'></div>
    
    <input name='add' type='button' id='add' value='Add Item'/>
    
    </body>
    </html>
    
    <script type="text/javascript">
    
    var item = document.getElementById('item');
    
    var stopper=0;
    
    document.getElementById('add').onclick = function () {
    
    stopper=stopper+1;
    
      var input = document.createElement('input'),
          div = document.createElement('div');
      input.type = "text";
      input.setAttribute("name", "item[]");
      input.setAttribute("class", "item");
    
      div.appendChild(input);
      //...
    
      item.appendChild(div);
    
    };
    </script>
    

    JS Fiddle

    How can I do this? Instead of text box, I want to dynamically generate a drop down (<select>). And the option of the drop down would be coming from my SQL database.

  • sta
    sta about 3 years
    A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.
  • Dinushika Rathnayake
    Dinushika Rathnayake about 3 years
    The answer also added