需要添加值以通过手动数据填充下拉列表

时间:2013-10-01 14:42:42

标签: jquery arrays option key-value html-select

请参阅链接:http://jsfiddle.net/NaUAL/

结果:

<select id="second-choice">
<option>Chips</option>
<option>Cookies</option>
</select>

欲望结果:

<select id="second-choice">
<option value="465">Chips</option>
<option value="984">Cookies</option>
</select>

我需要一种方法来为数据添加值并获得类似的输出...值应列在以下数据中: “base”:[“请从上面选择”],“饮料”:[“咖啡”,“可乐”],“零食”:[“薯条”,“饼干”]

2 个答案:

答案 0 :(得分:1)

DEMO

var data = {
        "base" : ["Please choose from above"],
        "beverages": ["Coffee_465","Coke_984"],
        "snacks": ["Chips_123","Cookies_987"]
}

分配数据键值,如optionText_optionValue

$.each(vals,function(i,val){
    var v = val.split('_'); //use split to break optionText and optionValue
    html.push('<option value="'+v[1]+'">'+v[0]+'</option>')
});

答案 1 :(得分:0)

$.each(vals,function(i,val)
{
   html.push('<option value='+value_variable+'>'+val+'</option>'); // value variable contains the actual value such as 465 or 984 or whatever.
});