Dodawanie opcji do jQuery?

Jak najłatwiej dodać option do listy rozwijanej używając jQuery?

Czy to zadziała?
$("#mySelect").append('<option value=1>My option</option>');
Author: Sometowngeek, 2009-04-11

27 answers

Zgadzam się Ashish, to nie działało w IE8 (jeszcze w FF):

$("#selectList").append(new Option("option text", "value"));

To zadziałało:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);
 144
Author: Josh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-11-30 12:56:37

Osobiście wolę tę składnię do dodawania opcji:

$('#mySelect').append($('<option>', {
    value: 1,
    text: 'My option'
}));

Jeśli dodajesz opcje z kolekcji przedmiotów, możesz wykonać następujące czynności:

$.each(items, function (i, item) {
    $('#mySelect').append($('<option>', { 
        value: item.value,
        text : item.text 
    }));
});
 694
Author: dule,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-21 21:01:00

Możesz dodać opcję używając następującej składni, możesz również odwiedzić opcję way handle w jQuery aby uzyskać więcej szczegółów.

  1. $('#select').append($('<option>', {value:1, text:'One'}));

  2. $('#select').append('<option value="1">One</option>');

  3. var option = new Option(text, value); $('#select').append($(option));

 89
Author: Dipu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-15 04:58:41

Jeśli nazwa lub wartość opcji jest dynamiczna, nie musisz się martwić o znaki specjalne; w tym przypadku możesz preferować proste metody DOM:

var s= document.getElementById('mySelect');
s.options[s.options.length]= new Option('My option', '1');
 43
Author: bobince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-11 15:46:30

Opcja 1 -

Możesz spróbować tego -

$('#selectID').append($('<option>',
 {
    value: value_variable,
    text : text_variable
}));

Like this -

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append($('<option>',
     {
        value: i,
        text : "Option "+i 
    }));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>

Opcja 2 -

Lub spróbuj tego -

$('#selectID').append( '<option value="'+value_variable+'">'+text_variable+'</option>' );

Like this -

for (i = 0; i < 10; i++)
{ 
     $('#mySelect').append( '<option value="'+i+'">'+'Option '+i+'</option>' );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id='mySelect'></select>
 33
Author: Abrar Jahin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-23 04:15:15

To działa dobrze.

Jeśli dodasz więcej niż jeden element opcji, zalecam wykonanie dopisania raz, a nie dopisanie każdego elementu.

 17
Author: Russ Cam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-11 14:51:44

Z jakiegokolwiek powodu Robienie $("#myselect").append(new Option("text", "text")); nie działa dla mnie w IE7+

I had to use $("#myselect").html("<option value='text'>text</option>");

 17
Author: Aurelio De Rosa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-29 23:21:36

Aby poprawić wydajność, powinieneś spróbować zmienić DOM tylko raz, tym bardziej, jeśli dodajesz wiele opcji.

var html = '';

for (var i = 0, len = data.length; i < len; ++i) {
    html.join('<option value="' + data[i]['value'] + '">' + data[i]['label'] + '</option>');
}           

$('#select').append(html);
 13
Author: John Magnolia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-10 13:50:42

Lubię używać podejścia non jquery:

mySelect.add(new Option('My option', 1));
 12
Author: caiohamamura,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-23 05:45:06

Możesz dodawać opcje dynamicznie do listy rozwijanej, jak pokazano w poniższym przykładzie. Tutaj w tym przykładzie wziąłem dane tablicy i powiązałem te wartości tablicy do rozwijanej, jak pokazano na zrzucie ekranu

Wyjście:

Tutaj wpisz opis obrazka

var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
   var myselect = $('<select>');
     $.each(resultData, function(index, key) {
	     myselect.append( $('<option></option>').val(key).html(key) );
       });
      $('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>

<select  id="selectCity">

</select>
 11
Author: GSB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-19 07:07:58
$('#mySelect').empty().append('<option value=1>My option</option>').selectmenu('refresh');
 10
Author: szpapas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-12 14:58:43

Nie wspomniano w żadnej odpowiedzi, ale przydatny jest przypadek, w którym chcesz, aby ta opcja była również wybrana, możesz dodać:

var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);
 8
Author: Eduard Florinescu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-18 08:57:11
var select = $('#myselect');
var newOptions = {
                'red' : 'Red',
                'blue' : 'Blue',
                'green' : 'Green',
                'yellow' : 'Yellow'
            };
$('option', select).remove();
$.each(newOptions, function(text, key) {
    var option = new Option(key, text);
    select.append($(option));
});
 8
Author: Salim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 07:38:47

To bardzo proste rzeczy. Możesz to zrobić w ten sposób

$('#select_id').append('<option value="five" selected="selected">Five</option>');

Lub

$('#select_id').append($('<option>', {
                    value: 1,
                    text: 'One'
                }));

Oto pełny przewodnik

 7
Author: Yesuus Yesuus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-07 16:29:22

Są dwa sposoby. Możesz użyć jednego z tych dwóch.

Pierwszy:

$('#waterTransportationFrom').append('<option value="select" selected="selected">Select From Dropdown List</option>');

Drugi:

$.each(dataCollecton, function(val, text) {            
    options.append($('<option></option>').val(text.route).html(text.route));
});
 4
Author: Dulith De Cozta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-22 12:41:35

Jeśli chcesz wstawić nową opcję w określonym indeksie w select:

$("#my_select option").eq(2).before($('<option>', {
    value: 'New Item',
    text: 'New Item'
}));

Spowoduje wstawienie" nowego elementu " jako trzeciego elementu w select.

 3
Author: ATOzTOA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-22 09:14:49

Możesz dodać i ustawić atrybut Value za pomocą tekstu:

$("#id").append($('<option></option>').attr("value", '').text(''));
$("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));
 3
Author: Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-12 19:59:54

Znaleźliśmy pewien problem, gdy dodajesz opcję i używasz jQuery validate. Musisz kliknąć jeden element na liście wybierz wiele. Dodasz ten kod do obsługi:

$("#phonelist").append("<option value='"+ 'yournewvalue' +"' >"+ 'yournewvalue' +"</option>");

$("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected

$('#phonelist option[value=' + 'yournewvalue' + ']').attr('selected', true); //add new selected

/ images/content/740195 / 6d7fd14507516b73294da522db6091ec.png

 3
Author: Peang Peang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-04 11:36:41

To tylko szybkie punkty za najlepszą wydajność

Zawsze, gdy masz do czynienia z wieloma opcjami, zbuduj duży ciąg, a następnie dodaj go do "wybierz" dla najlepszej wydajności

F. g.

Var $mySelect = $('#mySelect'); var str=";

$.each(items, function (i, item) {
    // IMPORTANT: no selectors inside the loop (for the best performance)
    str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string

$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');

Jeszcze szybciej

var str = ""; 
for(var i; i = 0; i < arr.length; i++){
    str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}    
$mySelect.html(str);
$mySelect.multiSelect('refresh');
 2
Author: Hatim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-25 02:11:54

Co powiesz na to

var numbers = [1, 2, 3, 4, 5];
var option = '';

for (var i=0;i<numbers.length;i++){
     option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
    }

    $('#items').append(option);
 2
Author: Mcfaith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-27 07:49:28

Jeśli U Masz optgroup wewnątrz select , U Masz błąd w DOM.

Myślę, że najlepszy sposób:

$("#select option:last").after($('<option value="1">my option</option>'));
 1
Author: DarveL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-07 10:55:55

U można spróbować poniżej kodu, aby dołączyć do opcji

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

    <script>
          $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
    </script>
 1
Author: Muhammad Kamal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-28 16:20:21
$('#select_id').append($('<option>',{ value: v, text: t }));
 1
Author: Cris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 21:40:32

Tak to zrobiłem, z przyciskiem do dodania każdego znacznika select.

$(document).on("click","#button",function() {
   $('#id_table_AddTransactions').append('<option></option>')
}
 1
Author: Ronald Valera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 19:25:45
$(function () {
     var option = $("<option></option>");
     option.text("Display text");
     option.val("1");
     $("#Select1").append(option);
});

Jeśli pobierasz dane z jakiegoś obiektu, po prostu prześlij ten obiekt do funkcji...

$(function (product) {
     var option = $("<option></option>");
     option.text(product.Name);
     option.val(product.Id);
     $("#Select1").append(option);
});

Nazwa i Id to nazwy obiektu properties...so możesz je nazywać jak chcesz...I oczywiście, jeśli macie tablicę...chcesz zbudować własną funkcję za pomocą pętli for...a następnie po prostu wywołaj tę funkcję w programie document ready...Cheers

 1
Author: Robert Nol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-13 22:28:18

Możesz to zrobić w ES6:

$.each(json, (i, val) => {
    $('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
  });
 1
Author: idiglove,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 08:19:32

Na podstawie odpowiedzi dule ' a do dodawania zbioru przedmiotów, jednolinijkowy for...in będzie też zdziałać cuda:

let cities = {'ny':'New York','ld':'London','db':'Dubai','pk':'Beijing','tk':'Tokyo','nd':'New Delhi'};

for(let c in cities){$('#selectCity').append($('<option>',{value: c,text: cities[c]}))}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<select  id="selectCity"></select>

Zarówno wartości obiektu, jak i indeksy są przypisane do opcji. To rozwiązanie działa nawet w starym jQuery (v1.4) !

 0
Author: CPHPython,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-18 13:39:26