Largoh Largoh - 6 months ago 31
Javascript Question

Update options on select click in chrome

I've discovered an issue with chrome while trying to update the options of a select element when a user clicks on said select element.
The system I'm working on basically works as per the JSFiddle below, except that the list of options are received via an ajax call, but even using an object produces the same result.

What appears to be happening is that when the user click and the options are displayed, it will only show 1 option. It will then populate the list of options but not update how many are displayed.

If you use the arrow keys to move up or down you can actually select the other options. The only way around it that I can find is to click off the select element and then click it again.

It works perfectly in IE and Firefox though.

A JSFiddle can be found here: http://jsfiddle.net/Largoh/Thz55/

HTML

<select id="selector">
<option value="2" selected>Option 2</option>
</select>


Javascript

$(function() {
$("#selector").click(function() {
if($("option", this).length < 2)
GetOptions(this);
});
});

function GetOptions(select) {
var Options = [
{ id: 1, text: "Option 1"},
{ id: 2, text: "Option 2"},
{ id: 3, text: "Option 3"},
{ id: 4, text: "Option 4"},
{ id: 5, text: "Option 5"},
{ id: 6, text: "Option 6"},
{ id: 7, text: "Option 7"}
];
$('option:first', select).remove();
for(var i = 0; i < Options.length;i++)
{
var option = $("<option/>");
option.val(Options[i].id).text(Options[i].text);
$(select).append(option);
}
}

Answer

Chrome doesn't update the UI when the select is open and the options are updated, so you could work around it by blurring the element & giving it focus again:

// Update the options first
$('option:first', select).remove();
for(var i = 0; i < Options.length;i++)
{
    var option = $("<option/>");
    option.val(Options[i].id).text(Options[i].text);
    $(select).append(option);
}
// Take focus away from the select
$(select).blur();
// Force the dropdown to open:
// http://stackoverflow.com/questions/10453393/how-to-open-the-select-input-using-jquery
var e = document.createEvent("MouseEvents");
e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
select.dispatchEvent(e);

http://jsfiddle.net/as68Y/

Keep in mind with this approach though - especially if the data source is AJAX - what if I go to click "Option 1" and it suddenly changes to "Option X". Not a great user experience. You'd be better off disabling the select element during this operation.