40

How do you create a dropdown list dynamically using jQuery? By dropdown list, I mean a <select> with its associated <option> values.

2
  • 3
    dropdown list? did you mean the <select> tag? Jan 27, 2011 at 9:23
  • Is it possible to provide a little more information?
    – Tim
    Jan 27, 2011 at 9:26

3 Answers 3

84

Just create the elements like any element.

Example:

var data = {
    'foo': 'bar',
    'foo2': 'baz'
}


var s = $('<select />');

for(var val in data) {
    $('<option />', {value: val, text: data[val]}).appendTo(s);
}

s.appendTo('body'); // or wherever it should be
3
  • c-sharpcorner.com/UploadFile/dhananjaycoder/… - Above link is explaining how the above answer working step by step .. It will helpful. Just look into that. :)
    – vinodh
    Sep 8, 2015 at 6:26
  • in my case do as below... How do I append it to the newly added html element ? I mean s.appendTo ( what?) var table = document.getElementById("demoGrid"); var row = table.insertRow(1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = "<input type='text' />" // I want dropdown list to be shown here for users to select
    – singhswat
    Apr 30, 2018 at 10:50
  • 1
    @singhswat: s.appendTo(cell1). Apr 30, 2018 at 15:59
10

In its simplest form,

var opt = "<option> -- Select -- </option>";

$(opt).wrap('<select />');

$('#some-container-div').html(opt);
3

http://hungred.com/how-to/tutorial-jquery-select-box-manipulation-plugin/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.