Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically add input type select with options in Javascript

I have found adding inputs to a form is quite simple in Javascript, but for some reason adding the select input with options is not working. The options are appearing outside of the dropdown.

Here's my code in jsfiddle: http://jsfiddle.net/LNVTQ/

Here's my code inline:

var choices=[];
choices[0]="one";
choices[1]="two";

function addInput(divName){
    var newDiv=document.createElement('div');
    newDiv.innerHTML="<select>";
    for(i=0; i<choices.length; i=i+1){
        newDiv.innerHTML=newDiv.innerHTML+"<option value='"+choices[i]+"'>"+choices[i]+"</option>";
    }
    newDiv.innerHTML=newDiv.innerHTML+"</select>";
    document.getElementById(divName).appendChild(newDiv);
}

And the HTML:

<form class="new" method="post" action="/jobs">
    <div id="dynamicInput"></div>
    <input type="button" value="Add" onclick="addInput('dynamicInput');" />
    <input type="button" value="Save" />
</form>

I will accept answers using jQuery or just vanilla Javascript.

like image 381
Jake Avatar asked Sep 07 '11 21:09

Jake


People also ask

How to Dynamically select option in Dropdown menu?

To add a dropdown list dynamically, you would need to create the HTML <select> element, its label and optionally a <br> tag. In pure JavaScript, you can use the document. createElement() method to programmatically create a dropdown list. Then you can call the Node's appendChild() method or jQuery's .


1 Answers

Pure Vanila JS

var choices = ["one", "two"];

function addInput(divName) {
    var newDiv = document.createElement('div');
    var selectHTML = "";
    selectHTML="<select>";
    for(i = 0; i < choices.length; i = i + 1) {
        selectHTML += "<option value='" + choices[i] + "'>" + choices[i] + "</option>";
    }
    selectHTML += "</select>";
    newDiv.innerHTML = selectHTML;
    document.getElementById(divName).appendChild(newDiv);
}
<form class="new" method="post" action="/jobs">
    <div id="dynamicInput"></div>
    <input type="button" value="Add" onclick="addInput('dynamicInput');" />
    <input type="button" value="Save" />
</form>


jQuery Version

var choices = ["one", "two"];

function addInput(divName) {
    var select = $("<select/>")
    $.each(choices, function(a, b) {
        select.append($("<option/>").attr("value", b).text(b));
    });
    $("#" + divName).append(select);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<form class="new" method="post" action="/jobs">
    <div id="dynamicInput"></div>
    <input type="button" value="Add" onclick="addInput('dynamicInput');" />
    <input type="button" value="Save" />
</form>
like image 121
Chandu Avatar answered Oct 27 '22 08:10

Chandu