-4

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 !

softdezire
  • 9
  • 2
  • 7

3 Answers3

3

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>");   
    }     
}
Inm0r74L
  • 205
  • 1
  • 7
1

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.

shauneba
  • 2,122
  • 2
  • 22
  • 32
  • Best answer, raw JavaScript is best solution in this case I think – karaxuna Oct 11 '12 at 11:29
  • 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
0

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>");
    });​
Shubhanshu Mishra
  • 6,210
  • 6
  • 21
  • 23