如何在HTML选择标记中显示默认选项值

时间:2015-07-21 07:01:36

标签: jquery html

我将动态值附加到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/

你能告诉我怎么做吗

2 个答案:

答案 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>'

DEMO

答案 1 :(得分:2)

select的值设置为空。这会将默认值设置为下拉列表。

$('#companieslist').val('');

Demo

或者,您可以从selected循环中删除option的{​​{1}}属性。这会将第一个for设置为已选中。

&#13;
&#13;
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;
&#13;
&#13;