简体   繁体   English

使用Javascript和jQuery自动填充选择框

[英]Auto populate select box using Javascript and jQuery

I have a select box: 我有一个选择框:

<select id="translationOptions" name="translationOptions"></select>

And I have a js array 我有一个js数组

var translationOptions = ["Egyptian Hieroglyphs", "Al Bhed (Final Fantasy X)", "Futurama"];

How would I auto populate the select box based on the var translationOptions ? 如何根据var translationOptions自动填充选择框?

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

What is the best way to add options to a select from an array with jQuery? 使用jQuery从数组中向select中添加选项的最佳方法是什么?

$.each(translationOptions, function(index, value) {
    $('#translationOptions').append($("<option />").val(index).text(value));
});

This uses text for display and index in the array for value. 这使用文本在数组中显示和索引值。

You can create options dynamically and append to select box in this way as well. 您可以动态创建选项并以这种方式附加到选择框。

jQuery.each(translationOptions, function(key, value) {
    jQuery('<option/>', {
       'value': key,
       'text' : value
}).appendTo('#translationOptions');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM