I need to populate a dropdown on clicking a HTML button using javascript or jQuery.Please suggest me some links if having. Any help/suggestions would be greatly appreciated ! Thanks !
-
1What did you tried? How do you get data? – Andrea Turri Oct 11 '12 at 11:14
-
1generate and append the option html to the dropdown while clicking the button. – Quicksilver Oct 11 '12 at 11:15
-
@Shawn Chin so are questions of this kind... – Salketer Oct 11 '12 at 11:24
-
Still haven't found valid Answer. All are making their points.Links referred here points to ASP Dropdownlist controls rather than valid answer. – softdezire Oct 11 '12 at 11:31
3 Answers
First bind a handler for click event on the button
("#myBtnId").click(function (){
populateDropDown();
});
Then make a function that populate the Dropdown
function populateDropdown(){
var $myDD = $("#myDropDownId");
$myDD.append("<option value='value'>Text</option>");
}
Notice if you have a list of items you just change the code for iterate over the list and put values and text for the options dinamically.
function populateDropdown(listOfItems){
var $myDD = $("#myDropDownId");
for (var i = 0; i<listOfItems.lenght; i++){
$myDD.append("<option value='"+ listOfItems[i].value +"'>"+listOfItems[i].text+"</option>");
}
}

- 205
- 1
- 7
It should be fairly straightforward.
You just need to either have an onclick event or use event binding for the button to call a function which will populate the dropdown.
E.g. <button type='button' onclick='Populate();'>Populate</button>
And then your JavaScript function simply adds in the values:
function Populate() {
var dropdown = document.getElementById("dropdown_id_here");
dropdown.options[0] = new Option('Text 1', 'Value1');
dropdown.options[1] = new Option('Text 2', 'Value2');
// And so on, add as many options as required.
}
There are undoubtedly dozens of ways to achieve this functionality so other solutions may suit you better or be simpler.

- 2,122
- 2
- 22
- 32
-
-
1@karaxuna Thanks, yeah I'll use jQuery if I'm already using it on a page, but no sense adding the overhead if it's not too necessary. – shauneba Oct 11 '12 at 13:05
Use the appendChild()
function of the select tag and keep adding your options. You can find the details at: http://www.w3schools.com/dom/met_element_appendchild.asp
You can also do it in jQuery using the append()
function: http://api.jquery.com/append/
You can have a look at the working code at: http://jsfiddle.net/shubhanshumishra/jHFZZ/
<input id="clickMe" value="clickme" type="button" />
<select id="dropdown">
<option value="0">Select Fields</option>
</select>
This is the Javascript:
$i=0;
$("#clickMe").click(function(e){
$i++;
$("#dropdown").append("<option value='"+$i+"'>New Field</option>");
});

- 6,210
- 6
- 21
- 23