Javascript добавить в select option

What is the best way to add options to a select from a JavaScript object with jQuery?

What is the best method for adding options to a

selectValues = < "1": "test 1", "2": "test 2" >; for (key in selectValues) < if (typeof (selectValuesJavascript добавить в select option == 'string') < $('#mySelect').append(''); > > 
$.each(selectValues, function(key, value) < $('#mySelect') .append($('', < value : key >) .text(value)); >); 

Changes from matdumsa’s: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().

maybe of help: texotela.co.uk/code/jquery/select (it was a help for me after i stumbled upon this question)

The cleaned up version listed above only works in Jquery 1.4+. For older versions use the one in matdumsa’s answer

The title should be instead «What is the best way to add options to a select from a JSON object whith jQuery?

37 Answers 37

The same as other answers, in a jQuery fashion:

$.each(selectValues, function(key, value) ") .attr("value", key) .text(value)); >); 

I would first of all assign $(«#mySelect») to a var, otherwise calling $(«#mySelect») every time inside the loop is very wasteful, as is updating the DOM. See points #3 and #6 at artzstudio.com/2009/04/jquery-performance-rules/…

var output = []; $.each(selectValues, function(key, value) < output.push(''); >); $('#mySelect').html(output.join('')); 

In this way you «touch the DOM» only one time.

Читайте также:  Find php database password

I’m not sure if the latest line can be converted into $(‘#mySelect’).html(output.join(»)) because I don’t know jQuery internals (maybe it does some parsing in the html() method)

You method is obviously the faster one than the ‘correct’ answer above since it uses less jQuery too.

This is slightly faster and cleaner.

var selectValues = < "1": "test 1", "2": "test 2" >; var $mySelect = $('#mySelect'); // $.each(selectValues, function(key, value) < var $option = $("", < value: key, text: value >); $mySelect.append($option); >);

It think it will be a better idea to cache ` $(‘#mySelect’)` , so that you look up only once before the loop. Currently it is searching the DOM for the element for every single option .

jQuery

var list = $("#selectList"); $.each(items, function(index, item) < list.append(new Option(item.text, item.value)); >); 

Vanilla JavaScript

var list = document.getElementById("selectList"); for(var i in items)

If you don’t have to support old IE versions, using the Option constructor is clearly the way to go, a readable and efficient solution:

$(new Option('myText', 'val')).appendTo('#mySelect'); 

It’s equivalent in functionality to, but cleaner than:

$(" ").attr("value", "val").text("myText")).appendTo('#mySelect'); 

This looks nicer, provides readability, but is slower than other methods.

$.each(selectData, function(i, option) < $("").val(option.id).text(option.title).appendTo("#selectBox"); >); 

If you want speed, the fastest (tested!) way is this, using array, not string concatenation, and using only one append call.

auxArr = []; $.each(selectData, function(i, option) < auxArr[i] = ""; >); $('#selectBox').append(auxArr.join('')); 

It seems that plain .append also works as expected,

$("#mySelect").append( $.map(selectValues, function(v,k)< return $("").val(k).text(v); >) ); 
$("#mySelect").append( $.map(selectValues, (v,k) => $("").val(k).text(v)) // $.map(selectValues, (v,k) => new Option(v, k)) // using plain JS ); 

All of these answers seem unnecessarily complicated. All you need is:

var options = $('#mySelect').get(0).options; $.each(selectValues, function(key, value) < options[options.length] = new Option(value, key); >); 

That is completely cross browser compatible.

Be forwarned. I am using jQuery Mobile 1.0b2 with PhoneGap 1.0.0 on an Android 2.2 (Cyanogen 7.0.1) phone (T-Mobile G2) and could not get the .append() method to work at all. I had to use .html() like follows:

var options; $.each(data, function(index, object) < options += ''; >); $('#selectMenu').html(options); 
 var output = []; var length = data.length; for(var i = 0; i < length; i++) < output[i++] = ''; > $('#choose_schedule').get(0).innerHTML = output.join(''); 

I’ve done a few tests and this, I believe, does the job the fastest. 😛

There’s an approach using the Microsoft Templating approach that’s currently under proposal for inclusion into jQuery core. There’s more power in using the templating so for the simplest scenario it may not be the best option. For more details see Scott Gu’s post outlining the features.

First include the templating js file, available from github.

Then with your data call the .render() method

var someData = [ < Text: "one", Value: "1" >, < Text: "two", Value: "2" >, < Text: "three", Value: "3">]; $("#templateOptionItem").render(someData).appendTo("#mySelect"); 

I’ve blogged this approach in more detail.

I have made something like this, loading a dropdown item via Ajax. The response above is also acceptable, but it is always good to have as little DOM modification as as possible for better performance.

So rather than add each item inside a loop it is better to collect items within a loop and append it once it’s completed.

Most of the other answers use the each function to iterate over the selectValues . This requires that append be called into for each element and a reflow gets triggered when each is added individually.

Updating this answer to a more idiomatic functional method (using modern JS) can be formed to call append only once, with an array of option elements created using map and an Option element constructor.

Using an Option DOM element should reduce function call overhead as the option element doesn’t need to be updated after creation and jQuery’s parsing logic need not run.

$('mySelect').append($.map(selectValues, (k, v) => new Option(k, v))) 

This can be simplified further if you make a factory utility function that will new up an option object:

const newoption = (. args) => new Option(. args) 

Then this can be provided directly to map :

$('mySelect').append($.map(selectValues, newoption)) 

Previous Formulation

Because append also allows passing values as a variable number of arguments, we can precreate the list of option elements map and append them as arguments in a single call by using apply .

$.fn.append.apply($('mySelect'), $.map(selectValues, (k, v) => $("").val(k).text(v))); 

It looks like that in later versions of jQuery, append also accepts an array argument and this can be simplified somewhat:

$('mySelect').append($.map(selectValues, (k, v) => $("").val(k).text(v))) 

Источник

HTMLSelectElement: add() method

The HTMLSelectElement.add() method adds an element to the collection of option elements for this select element.

Syntax

Parameters

An element of the collection, or an index of type long, representing the item should be inserted before. If this parameter is null (or the index does not exist), the new element is appended to the end of the collection.

Return value

Exceptions

Thrown if the item passed to the method is an ancestor of the HTMLSelectElement .

Examples

Creating Elements from Scratch

const sel = document.createElement("select"); const opt1 = document.createElement("option"); const opt2 = document.createElement("option"); opt1.value = "1"; opt1.text = "Option: Value 1"; opt2.value = "2"; opt2.text = "Option: Value 2"; sel.add(opt1, null); sel.add(opt2, null); /* Produces the following, conceptually:  */ 

The before parameter is optional. So the following is accepted.

Append to an Existing Collection

const sel = document.getElementById("existingList"); const opt = document.createElement("option"); opt.value = "3"; opt.text = "Option: Value 3"; sel.add(opt, null); /* Takes the existing following select object:  And changes it to:  */ 

The before parameter is optional. So the following is accepted.

Inserting to an Existing Collection

const sel = document.getElementById("existingList"); const opt = document.createElement("option"); opt.value = "3"; opt.text = "Option: Value 3"; sel.add(opt, sel.options[1]); /* Takes the existing following select object:  And changes it to:  */ 

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Adding options to select with javascript

Voting to reopen, as the linked ‘duplicate’ only has jQuery-based answers, whereas this one requires (or at least implies a requirement of) plain JavaScript.

11 Answers 11

You could achieve this with a simple for loop:

var min = 12, max = 100, select = document.getElementById('selectElementId'); for (var i = min; i

JS Perf comparison of both mine and Sime Vidas’ answer, run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.

Edited in response to comment from OP:

[How] do [I] apply this to more than one element?
function populateSelect(target, min, max) < if (!target)< return false; >else < var min = min || 0, max = max || min + 100; select = document.getElementById(target); for (var i = min; i> > // calling the function with all three values: populateSelect('selectElementId',12,100); // calling the function with only the 'id' ('min' and 'max' are set to defaults): populateSelect('anotherSelect'); // calling the function with the 'id' and the 'min' (the 'max' is set to default): populateSelect('moreSelects', 50); 

And, finally (after quite a delay. ), an approach extending the prototype of the HTMLSelectElement in order to chain the populate() function, as a method, to the DOM node:

HTMLSelectElement.prototype.populate = function (opts) < var settings = <>; settings.min = 0; settings.max = settings.min + 100; for (var userOpt in opts) < if (opts.hasOwnProperty(userOpt)) < settings[userOpt] = opts[userOpt]; >> for (var i = settings.min; i >; document.getElementById('selectElementId').populate(< 'min': 12, 'max': 40 >); 

Источник

Оцените статью