Adding options to a <select> using jQuery?

后端 未结 30 1667
萌比男神i
萌比男神i 2020-11-22 03:56

What\'s the easiest way to add an option to a dropdown using jQuery?

Will this work?

$(\"#mySelect\").append(\'
相关标签:
30条回答
  • 2020-11-22 04:26

    How about this

    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);
    
    0 讨论(0)
  • 2020-11-22 04:27
    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));
    });
    
    0 讨论(0)
  • 2020-11-22 04:27

    if u have optgroup inside select, u got error in DOM.

    I think a best way:

    $("#select option:last").after($('<option value="1">my option</option>'));
    
    0 讨论(0)
  • 2020-11-22 04:28

    Based on dule's answer for appending a collection of items, a one-liner for...in will also work wonders:

    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>

    Both object values and indexes are assigned to the options. This solution works even in the old jQuery (v1.4)!

    0 讨论(0)
  • 2020-11-22 04:29

    U can try below code to append to option

      <select id="mySelect"></select>
    
        <script>
              $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption"));
        </script>
    
    0 讨论(0)
  • 2020-11-22 04:30

    Personally, I prefer this syntax for appending options:

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

    If you're adding options from a collection of items, you can do the following:

    $.each(items, function (i, item) {
        $('#mySelect').append($('<option>', { 
            value: item.value,
            text : item.text 
        }));
    });
    
    0 讨论(0)
提交回复
热议问题