selectize.js icon indicating copy to clipboard operation
selectize.js copied to clipboard

Backspace required to clear input field with "empty" option

Open themikeb opened this issue 11 years ago • 16 comments

We were using version 0.9.1 and noticed an issue where a backspace was required to clear an input field when an "empty" option was the selected option. Issue #163 seemed to address this, in words. We upgraded to version 0.11.2 and the issue still remains. I've traced through the plugin code but was unable to locate the source of the problem within a reasonable time. Hoping you can help. We do have a workaround but would like to have some information on the problem.

The key seems to be whether a value attribute is specified on the original

testSelect1 will exhibit the undesired behavior of requiring a backspace to clear the input field. testSelect2 works as we would expect.

Thanks in advance for looking into this.

themikeb avatar Jan 13 '15 20:01 themikeb

Can you post some sample code that demonstrates the problem – preferably a jsfiddle?

brianreavis avatar Jan 28 '15 02:01 brianreavis

Hi Brian, I sure will. I'll get to that this weekend and drop a line when here when I have it done.

themikeb avatar Jan 29 '15 16:01 themikeb

http://jsfiddle.net/kc7gL82y/ Demonstrates the problem where a backspace is required to clear the input.

themikeb avatar Jan 30 '15 20:01 themikeb

Maybe this is related to https://github.com/brianreavis/selectize.js/pull/477. In general for a single selection, selectize.js requires to clear the option with backspace. You cannot simply start to enter anything unless the selection is cleared. I have some users which bug me constantly asking me to fix it :)

vzemlys avatar Feb 02 '15 09:02 vzemlys

I don't see this as a usability problem. What I see as a "nagging feature", is when you hit backspace and selectize highlights the first option from the dropdown and when hitting enter/tab to go to next element, it selects it.

dresende avatar Feb 24 '15 12:02 dresende

Forget about my comment, was using an old version. Updated and now have selectOnTab option (yeay!)

dresende avatar Feb 24 '15 12:02 dresende

This issue was pretty irritating for me. It took me a minute to figure out what was even going on, as nothing was present in the field, but I still couldn't type anything. I created a plugin to solve the problem, and I'm copying my solution over here in case anyone hits this page via google, like I did.

I tried luanfonceca's solution in #647, but found it contained an infinite loop and a few bugs. I'm guessing it was created for an older version of selectize.

I made several changes and got it working the way I expected. Code is below.

/**
 * Typing mode plugin by Luan Fonseca
 * December 2014
 * https://github.com/brianreavis/selectize.js/blob/5d81539d677e8c2411215a1fb81789a8006c77f2/src/plugins/typing_mode/plugin.js#L1
 *
 * Modified by Jess Mann
 * June 2017
 *
 * Selectize version 0.12.4
 */
Selectize.define('typing_mode', function(options) {
        var self = this;

        this.setup = (function() {
                var original = self.setup;
                self.updating = false;

                return function() {
                        original.apply(this, arguments);

                        this.on('dropdown_open', function() {
                                self.previousValue = self.getValue();
                                var option = self.getOption(self.previousValue);

                                /**
                                 * Two styles: 
                                 *     1) usePlaceholder gives an immediately blank field to type into
                                 *     2) default shows the text and allows user to edit last selection
                                 */
                                if (self.settings.usePlaceholder) {
                                        self.$control_input.attr('placeholder', option.text().trim());
                                } else {
                                        self.$control_input.attr('value', option.text().trim());
                                }

                                self.$control_input.css({
                                        opacity: '1',
                                        width: '100%',
                                        position: 'relative'
                                });
                                self.$control.find('.item').hide();

                                self.items = [];
                                self.setCaret(0);
                        });

                        this.$control_input.on('blur', function() {
                                self.$control.find('.item').show();

                                /**
                                 * I played with testing self.settings.allowEmptyOption
                                 *     before reverting to the previous value,
                                 *     but that doesn't seem to be intuitive behavior.
                                 *
                                 * Use the current value, or, if empty, set to the previous value
                                 */
                                var value = self.getValue() || self.previousValue;

                                /**
                                 * Avoid infinite loop. self.setValue calls blur() again
                                 *     even if we pass true to the second param.
                                 */
                                if (self.updating)
                                        return;

                                self.updating = true;
                                self.setValue(value);
                                self.updating = false;
                        });
                };
        })();
});

To use the plugin, include "typing_mode" in the plugins array, when you instantiate selectize. For example:

$('select').selectize({
    plugins: ['typing_mode'],
    persist: false,
    create: true
});

A new settings option was added: "usePlaceholder".

  • If true, it uses Luan's original design, replacing the visible value with a placeholder, and then replacing it if nothing is selected.
  • If false, it uses a (possibly) more intuitive feel, where the previous value is immediately editable, just like you never left the text area to begin with.

avranu avatar Jun 21 '17 21:06 avranu

@avranu i have some problem with your solution. Step to be reproduced:

1- Open the selectize and select one value 2- Open selectize again, but now click outside the selectize.

ghost avatar Sep 12 '17 05:09 ghost

Hey letscape. Thanks for the feedback. I just tried your steps and didn't see any unexpected behavior. I'm on chrome.

That said, I don't have a ton of time to support this at the moment, so I probably can't be off too much more help. You might be able to post to the forums and get someone else to tweak it a bit to your liking. Good luck!

avranu avatar Sep 12 '17 12:09 avranu

@avranu thanks, i was able to fix my problem. I'm on firefox 55.0.2 on linux (if that matter). Selectize version 0.12.4 (if that matter). Also i make easy to me to be used.

Selectize.define('typing_mode', function(options) {
    var self = this;

    this.setup = (function() {
        var original = self.setup;

        return function() {
            original.apply(this, arguments);
            if(self.settings.initUnselected)
                self.setValue("");

            this.on('dropdown_open', function() {
                self.previousValue = self.getValue();
                var option = self.getOption(self.previousValue);

                // Two styles: 
                //     1) usePlaceholder gives an immediately blank field to type into
                //     2) default shows the text only when it selected and allows user to edit last selection
                if (self.settings.usePlaceholder) {
                    self.$control_input.attr('placeholder', option.text().trim());
                } else {
                    self.setValue("");
                }

                self.$control_input.css({
                    opacity: '1',
                    width: '100%',
                    position: 'relative'
                });
                self.items = [];
                self.setCaret(0);
            });

            this.$control_input.on('blur', function() {
                // Use the current value, or, if empty, set to the previous value
                var value = self.getValue() || (self.settings.usePlaceholder ? self.previousValue : "");
                // Avoid infinite loop. self.setValue calls blur() again
                //     even if we pass true to the second param.
                if (value !== self.getValue()) {
                    self.setValue(value);
                }
            });
        };
    })();
});

$(window).on('load', function () {
    if($.fn.validator) {
        $.fn.validator.Constructor.INPUT_SELECTOR += ':not(.selectize-input input)';
    }

    $('select.selectize').each(function(index) {
        var selectize = $(this),
        options = {},
        type = selectize.data("type") || "normal";
        if (type === "single-placeholder") {
            options["plugins"] = ['typing_mode'];
            options["usePlaceholder"] = true;
            options["initUnselected"] = selectize.data("init-unselected") || true;
        } else if (type === "single-enhanced") {
            options["plugins"] = ['typing_mode'];
            options["initUnselected"] = selectize.data("init-unselected") || true;
        } else {
            if (selectize.data("init-unselected") || true)
                options["onInitialize"] = function() { this.setValue(""); };
        }
        
        options["create"] = selectize.data("create") || false;
        options["sortField"] = {
            field: 'text',
            direction: selectize.data("sort-order") || 'asc'
        };
        options["persist"] = selectize.data("sort-order") || false;
        options["disableDelete"] = selectize.data("disable-delete") || true;
        options["openOnFocus"] = selectize.data("open-focus") || true;

        $(this).selectize(options);
    });
});

ghost avatar Sep 12 '17 15:09 ghost

I think will be really nice that this could be merged with the master. I'm also another, this not irritate me at all, but i think is really a nice feature to have.

ghost avatar Sep 12 '17 15:09 ghost

The quickest solution that worked for me:

onDropdownOpen: function () {
    this.clear();
}

kobykorman avatar May 01 '18 12:05 kobykorman

Thanks @legshooter you saved my time.

Krishnankk avatar May 17 '18 14:05 Krishnankk

legshooter's solution works well, but it resets selection if some option is already selected. This solution fixes that issue:

  onDropdownOpen: function () {
                        var self = this;
                        var value =  self.getValue();
                        value = value || "";
                        if (!value.length) {
                            self.clear();
                            return;
                        }

tcapb avatar Oct 14 '18 03:10 tcapb

@tcapb there is a } missing at the end!

One problem with this solution is, that the onChange-Trigger is fired on opening the dropdown.

buzanits avatar Dec 11 '18 09:12 buzanits

closing stale issues older than one year. If this issue was closed in error please message the maintainers. All issues must include a proper title, description, and examples.

risadams avatar Dec 01 '20 14:12 risadams