I am appending dynamic values to the HTML Select .
I am doing it this way
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);
The last value is being shown in the HTML Select , is it possible to show All Companies as the first value ??
This is my jsfiddle
https://jsfiddle.net/cf7hnvcq/1/
Could you please let me know how to do this
Only the option you want to see by default should have the selected
attribute.
Line 20 should be:
var companies = '<option value="" selected>All Companies</option>';
and line 22 should be:
companies += '<option value="' + response.companies[i].companyID + '">' + response.companies[i].companyName + '</option>'
Set the value of select
to empty. This will set the default value to the dropdown.
$('#companieslist').val('');
OR, You can remove the selected
attribute of option
from the for
loop. This will set the first option
as selected.
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);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <div> <select id="companieslist" name="companieslist"></select> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.