dan04 dan04 - 4 months ago 49
jQuery Question

Overwriting default selection in Selectize dropdown list

I recently modified a webpage to replace a non-user-friendly search control with a Selectize Single Item Select.

But I'm having one little UI annoyance. When you click on the control and then try typing in a new selection, nothing happens; it still has the default option. You first have to press Backspace to delete the default selection, and then you can enter a new search.

How can I make typing immediately overwrite the default option, without having to press Backspace?

Here's a short HTML example that demonstrates the issue:

<!DOCTYPE html>
<html>
<head>
<title>Selectize Example</title>
<link rel="stylesheet" href="Selectize/css/selectize.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript" src="Selectize/js/standalone/selectize.js" type="text/javascript"></script>
</head>
<body>
<select name="Manufacturer" id="Manufacturer" class="selectize">
<option value="ALL" selected>All Manufacturers</option>
<option value="1">Acme Corp.</option>
<option value="2">Contoso Ltd.</option>
<option value="3">Electronic, Inc.</option>
</select>
<script type="text/javascript">
$(".selectize").selectize({create: false})
</script>
</body>
</html>

Answer

I did it on the go, it surely needs improvements, but at least it works as expected.

Edit your javascript as follows:

$(".selectize").selectize({
    create: false,
    onDropdownOpen: function(dropdown) {
        var that = $(dropdown).prev().find('.item');

        // If the default option is selected, we empty the div acting as input.
        if(that.data('value') == 'ALL') {
            that.html('');
        }
    },
    onDropdownClose: function(dropdown) {
        var that = $(dropdown).prev().find('.item');

        // If nothing was selected, we restore initial value
        if(that.data('value') == 'ALL') {
            that.html('All Manifacturers');
        }
    },
});

I made a little jsfiddle too, check it.

It is quite self explanating, anyway it checks the value selected when the dropdown shows up, then again when it disappear and do the logic only if the selected value is the default.