Adding options to a <select> using jQuery?

后端 未结 30 1691
萌比男神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: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($('
    
    

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

提交回复
热议问题