[javascript] JQuery create new select option

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.    

This question is related to javascript jquery html jquery-selectors

The answer is


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');
    });
}

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>

How about

$('#county').append(
    $('<option />')
        .text('Select a city / town in Sweden')
        .val(''),
    $('<option />')
        .text('Melbourne')
        .val('Melbourne')
);

What about

var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value