简体   繁体   中英

Select drop down sort order in IE8

I have a select drop down on a web form, that is populated based on options selected in input fields prior to this on the form.

The form uses AJAX/JSON to get the list of options back from the server which it will use to populate the select.

I have a loop in my Javascript code that loops over the JSON response object in order to populate the select.

The response object will have data in the form of key/value pairs (both string values) as such:

" " - Please select, 45 - Optical, 52 - Dental, 67 - Surgery, 83 - Osteopath etc etc..

The code to populate the select I am using is:

$.each(response, function(key,value) {
    $("#benefitField4").append("<option value="+key+">"+value+"</option>");
}

... where 'benefitField4' is the id of the select on the form.

I need the results in the select shown in key order, so with 'Please select' having a key value of " ", I would hope this would be first.

Now in all browsers the resulting select displays the drop down in the right order, with 'Please select' being the first option.

In IE8 however, 'Please select' is 3rd in the list, with 'Optical' being first.

I have tried sorting the select by using this code:

var selectList = $('#benefitField4 option');
selectList.sort(function(a,b){
a = a.value;
b = b.value;
return a-b;
});
$('#benefitField4').empty()
$('#benefitField4').eq(0).html(selectList);

But this results in the last item in the select being shown (in this case Osteopath) as the initial value in the select, with 'Please select' being the last. Again, only in IE8.

As I need this to work in all browsers, I'm a bit lost as to why IE8 is behaving this way.

Can anyone help please?

I have found that this forces IE8 to pick the 'Please select' as the default select option:

$('#benefitField4 option[value="0"]').attr("selected",true);

For some reason it was ignoring the 'eq(0)'. Strange.

So all good. Thanks to those that commented.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM