我有这种格式的JSON:
"states": [
{"state":"AL","stateDescription":"Alabama","featured":"A1"},
{"state":"AK","stateDescription":"Alaska","featured":"B1"}
]
我正在填充一个下拉菜单,我一直在尝试将选项值分配给State,并将值显示给stateDescription,但不断出现错误。我在这里尝试过几个教程,但似乎都没有。
这是填充下拉列表的代码:
function populateDropdown(data) {
var info = JSON.parse(data);
var getStateDesc = _.pluck(info.states, 'stateDescription');
var renderOptions = _.map(getStateDesc, function (val) {
return '<option value="' + val + '">' + val + '</option>';
}).join();
$('#myComboBox').html(renderOptions).selectpicker("refresh");
};
所以这成功地填充了下拉菜单,但是选项值与描述相同,所以当我试图在以后删除它时它不起作用,因为值必须是'state'而不是stateDescription。
如何让第一个<option value="' + val + '">'
与州相等?
由于
答案 0 :(得分:1)
尝试
$(document).ready(function () {
var data = {
"states": [{
"state": "AL",
"stateDescription": "Alabama",
"featured": "A1"
}, {
"state": "AK",
"stateDescription": "Alaska",
"featured": "B1"
}]
}
$(data.states).each(function (i) {
$("#myComboBox").append($("<option/>", {
val: this.state,
html: this.stateDescription
}));
});
});
<强> HTML 强>
<select id="myComboBox"></select>
首先,你的json无效。您在开始和结束时需要{
和}
。然后你可以遍历json。使用.append()
方法添加选项选项。
答案 1 :(得分:0)
试试这个
var jso={
"states": [
{
"state": "AL",
"stateDescription": "Alabama",
"featured": "A1"
},
{
"state": "AK",
"stateDescription": "Alaska",
"featured": "B1"
}
]
}
function populateDropdown() {
var output='';
var dat= jso.states;
for(var i in dat)
{
output+= '<option value="' + dat[i].state + '">' + dat[i].stateDescription + '</option>';
}
$('#myComboBox').html(output).selectpicker("refresh");
}
populateDropdown();