dan04 dan04 - 1 year ago 151
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>
<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>
<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>
<script type="text/javascript">
$(".selectize").selectize({create: false})

Answer Source

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

Edit your javascript as follows:

    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') {
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download