Adding options to a <select> using jQuery?

后端 未结 30 1642
萌比男神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:12

    This did NOT work in IE8 (yet did in FF):

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

    This DID work:

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

    Option 1-

    You can try this-

    $('#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>

    Option 2-

    Or try this-

    $('#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>

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

    Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

    var o = new Option("option text", "value");
    o.selected=true;
    $("#mySelect").append(o);
    
    0 讨论(0)
  • 2020-11-22 04:14

    If you want to insert the new option at a specific index in the select:

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

    This will insert the "New Item" as the 3rd item in the select.

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

    You can append and set the Value attribute with text:

    $("#id").append($('<option></option>').attr("value", '').text(''));
    $("#id").append($('<option></option>').attr("value", '4').text('Financial Institutions'));
    
    0 讨论(0)
  • 2020-11-22 04:16

    You can do this in ES6:

    $.each(json, (i, val) => {
        $('.js-country-of-birth').append(`<option value="${val.country_code}"> ${val.country} </option>`);
      });
    
    0 讨论(0)
提交回复
热议问题