38

I have the below functions in regular JavaScript creating select options. Is there a way I can do this with jQuery without having to use the form object? Perhaps storing the options as an array of JSON objects and parsing this in the calling function...

function populate(form)
{
form.options.length = 0;
form.options[0] = new Option("Select a city / town in Sweden","");
form.options[1] = new Option("Melbourne","Melbourne");
}

Below is how I call the function above:

populate(document.form.county); //county is the id of the dropdownlist to populate.    
Ram
  • 3,092
  • 10
  • 40
  • 56
van
  • 9,159
  • 19
  • 60
  • 93

6 Answers6

68

Something like:

function populate(selector) {
  $(selector)
    .append('<option value="foo">foo</option>')
    .append('<option value="bar">bar</option>')
}

populate('#myform .myselect');

Or even:

$.fn.populate = function() {
  $(this)
    .append('<option value="foo">foo</option>')
    .append('<option value="bar">bar</option>')
}

$('#myform .myselect').populate();
Harold1983-
  • 3,329
  • 2
  • 23
  • 22
52

What about

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);
andrew.fox
  • 7,435
  • 5
  • 52
  • 75
Tejs
  • 40,736
  • 10
  • 68
  • 86
  • 22
    With jQuery 1.4+, you could just do this: `$('', { value : 'myValue' }).text('myText').appendTo('#country');` – Mottie May 04 '10 at 19:01
  • 6
    it's slightly more efficient to build up the list of options, then append them to the DOM, so you don't cause a reflow each time. see https://developers.google.com/speed/articles/reflow and http://stackoverflow.com/questions/510213/when-does-reflow-happen-in-a-dom-environment – zedd45 Apr 02 '14 at 15:35
  • Very elegant way! Good one. – Keshav May 20 '17 at 15:45
15

How about

$('#county').append(
    $('<option />')
        .text('Select a city / town in Sweden')
        .val(''),
    $('<option />')
        .text('Melbourne')
        .val('Melbourne')
);
CaffGeek
  • 21,856
  • 17
  • 100
  • 184
12

If you need to make single element you can use this construction:

$('<option/>', {
    'class': this.dataID,
    'text': this.s_dataValue
}).appendTo('.subCategory');

But if you need to print many elements you can use this construction:

function printOptions(arr){
    jQuery.each(arr, function(){
        $('<option/>', {
            'value': this.dataID,
            'text': this.s_dataValue
        }).appendTo('.subCategory');
    });
}
mdBender
  • 369
  • 2
  • 8
6

A really simple way to do this...

// create the option
var opt = $("<option>").val("myvalue").text("my text");

//append option to the select element
$(#my-select).append(opt);

This could be done in lots of ways, even in a single line if really you want to.

Tony Norcross
  • 73
  • 1
  • 4
5

This is confusing. When you say "form object", do you mean "<select> element"? If not, your code won't work, so I'll assume your form variable is in fact a reference to a <select> element. Why do you want to rewrite this code? What you have has worked in all scriptable browsers since around 1996, and won't stop working any time soon. Doing it with jQuery will immediately make your code slower, more error-prone and less compatible across browsers.

Here's a function that uses your current code as a starting point and populates a <select> element from an object:

<select id="mySelect"></select>

<script type="text/javascript>

function populateSelect(select, optionsData) {
    var options = select.options, o, selected;
    options.length = 0;
    for (var i = 0, len = optionsData.length; i < len; ++i) {
        o = optionsData[i];
        selected = !!o.selected;
        options[i] = new Option(o.text, o.value, selected, selected);
    }
}

var optionsData = [
    {
        text: "Select a city / town in Sweden",
        value: ""
    },
    {
        text: "Melbourne",
        value: "Melbourne",
        selected: true
    }
];

populateSelect(document.getElementById("mySelect"), optionsData);

</script>
Tim Down
  • 318,141
  • 75
  • 454
  • 536