我将动态值附加到HTML Select。
我这样做
var response = {
"companies": [{
"companyID": 2,
"companyName": "RAvi Corporation Ltd."
}, {
"companyID": 3,
"companyName": "Kiran Cement Ltd."
}, {
"companyID": 4,
"companyName": "ACC Ltd."
}]
}
var companies = '<option value="">All Companies</option>';
for (var i = 0; i < response.companies.length; i++) {
companies += '<option value="' + response.companies[i].companyID + '" selected>' + response.companies[i].companyName + '</option>'
}
$("#companieslist").html(companies);
最后一个值显示在HTML Select中,是否可以将所有公司显示为第一个值?
这是我的jsfiddle
https://jsfiddle.net/cf7hnvcq/1/
你能告诉我怎么做吗
答案 0 :(得分:3)
默认情况下,您只想看到的选项应具有selected
属性。
第20行应该是:
var companies = '<option value="" selected>All Companies</option>';
和第22行应该是:
companies += '<option value="' + response.companies[i].companyID + '">' + response.companies[i].companyName + '</option>'
答案 1 :(得分:2)
将select
的值设置为空。这会将默认值设置为下拉列表。
$('#companieslist').val('');
或者,您可以从selected
循环中删除option
的{{1}}属性。这会将第一个for
设置为已选中。
option
&#13;
var response = {
"companies": [{
"companyID": 2,
"companyName": "RAvi Corporation Ltd."
}, {
"companyID": 3,
"companyName": "Kiran Cement Ltd."
}, {
"companyID": 4,
"companyName": "ACC Ltd."
}]
};
var companies = '<option value="">All Companies</option>';
for (var i = 0; i < response.companies.length; i++) {
companies += '<option value="' + response.companies[i].companyID + '">' + response.companies[i].companyName + '</option>'; // Remove selected attribute from here
}
$("#companieslist").html(companies);
&#13;