Search code examples
jqueryjquery-pluginsvirtual-keyboard

Mottie's Virtual Keyboard close on validate true


I am using the jQuery on-screen keyboard plugin with a touchscreen. On my input I want to close the keyboard when I have reached 4 characters. Unfortunately, the keyboard only know when I have reached 4 characters and can limit the maximum input to 4 characters. The user still has to close manually the keyboard. Is there a code to close the keyboard ? Here is my actual script :

$('#password').keyboard({
        layout: 'custom',
        customLayout: {
            'default' : [
                'C D E F',
                '8 9 A B',
                '4 5 6 7',
                '0 1 2 3',
                '{bksp} {a} {c}'
            ]
        },
        usePreview : false,
        autoAccept: true,
        maxLength : 4,
        // Prevent keys not in the displayed keyboard from being typed in
        restrictInput : true,
        // include lower case characters (added v1.25.7)
        restrictInclude : 'a b c d e f',
        // don't use combos or A+E could become a ligature
        useCombos : false,
        // activate the "validate" callback function
        acceptValid : true,
        validate : function(keyboard, value, isClosing){
            // only make valid if input is 4 characters in length
            if(value.length === 4)
                return true; // I want to close the keyboard here

            return false;
        }
    });

Solution

  • Initially, I was going to suggest adding a setTimeout in the change callback, but then I noticed javascript errors popping up because the keyboard was closing and the "keyup" event was still firing.

    Anyway, I fixed those errors and added a new autoAcceptOnValid option - use it as follows (demo):

    $(function() {
    
      $('#password').keyboard({
        layout: 'custom',
        customLayout: {
          'default': [
            'C D E F',
            '8 9 A B',
            '4 5 6 7',
            '0 1 2 3',
            '{bksp} {a} {c}'
          ]
        },
        usePreview: false,
        autoAccept: true,
        maxLength: 4,
        // Prevent keys not in the displayed keyboard from being typed in
        restrictInput: true,
        // include lower case characters (added v1.25.7)
        restrictInclude: 'a b c d e f',
        // don't use combos or A+E could become a ligature
        useCombos: false,
        // activate the "validate" callback function
        acceptValid: true,
        // option added in v1.25.29
        autoAcceptOnValid: true,
        validate: function(keyboard, value, isClosing) {
          return value.length === 4;
        }
      });
    
    });