Search code examples
javascriptjqueryjquery-pluginsjquery-selectorsvirtual-keyboard

Mottie virtual keyboard and Chosen Selector


I am trying to get the following two excellent jQuery plugins to work together.

  • virtual keyboard plugin by Mottie: (github.com/Mottie/Keyboard)
  • a selector called Chosen which does filtering of the options as the user types: (harvesthq.github.io/chosen/) Here is an example of what I mean (when I use my physical keyboard): chosen auto-filtering while typing with physical keyboard

Unfortunately this filtering does not happen when I use mottie's keyboard. Here is a screenshot of what happens: chosen auto-filtering while typing with mottie fails

My mottie javascript is:

$('input, textarea').keyboard({layout: 'qwerty', usePreview: false, autoAccept: true}).addTyping();

Any idea why? Probably this question could be answered by the two developers (@mottie)

PS: Since need 10 points to post images I have them as links.


Solution

  • You'll need to use the select2 open event to initialize the keyboard (demo)

    var keys = {
        bksp: 8,
        tab: 9,
        enter: 13,
        space: 32,
        delete: 46
    };
    
    $('select')
        .select2({
            placeholder: "Select a state"
        })
        .on("select2:open", function (e) {
            $('.select2-container--open .select2-search__field').keyboard({
                // Used by jQuery UI position utility
                position: {
                    // null = attach to input/textarea;
                    // use $(sel) to attach elsewhere
                    of: $(document),
                    my: 'center bottom',
                    at: 'center bottom',
                    // used when "usePreview" is false
                    at2: 'center bottom'
                },
                reposition: true,
                usePreview: false,
                change: function(e, keyboard, el) {
                    var key = (keyboard.last.key || '').toLowerCase();
                    // trigger a keydown for "special" keys
                    e.type = keys[key] ? 'keydown' : 'input';
                    e.which = keys[key] || key.charCodeAt(0);
                    keyboard.$el.trigger(e);
                }
            })
            // activate the typing extension
            .addTyping({
                showTyping: true,
                delay: 50
            });
        });
    

    Update: special key interaction added to allow pressing enter on the virtual keyboard

    Include this css to remove the blue outline:

    .ui-keyboard-input-current {
        -moz-box-shadow: none;
        -webkit-box-shadow: none;
        box-shadow: none;
    }