Adding options to a <select> using jQuery?

后端 未结 30 1669
萌比男神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:34
    $('#select_id').append($('<option>',{ value: v, text: t }));
    
    0 讨论(0)
  • 2020-11-22 04:36

    You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot

    Output:

    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>

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

    That works well.

    If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.

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

    for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

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

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

    This is just a quick points for best performance

    always when you are dealing with many options, build a big string and then add it to the 'select' for best performance

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

    Even faster

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

    Try

    mySelect.innerHTML+= '<option value=1>My option</option>';
    

    btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
    <button id="btn">Add option</button>
    
    <select id="mySelect"></select>

    0 讨论(0)
提交回复
热议问题