Adding options to a select using jQuery

Posted in :

之前有試過動態加 <div> 到某個節點: Creating a div element in jQuery
https://stackoverflow.max-everyday.com/2023/02/creating-a-div-element-in-jquery/

今天要學的是把 array 裡的值, 變成 <select> 裡的 option.
https://stackoverflow.com/questions/740195/adding-options-to-a-select-using-jquery

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

$.each(selectValues, function(key, value) {   
     $('#mySelect')
         .append($("<option></option>")
                    .attr("value", key)
                    .text(value)); 
});

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *