Search code examples
javascriptjquerykeyboardvirtual-keyboard

Mottie Keyboard: Change focus when input field equals maxlength


I will make input automatically change focus to next input if input field equals maxlength. The input field is integrated with Mottie Keyboard. Is it possible to do this?

Here's DEMO : JSFIDDLE

If Virtual Keyboard is not used, it's easy to use this code:

$("input").bind("input", function() {
        var $this = $(this);
        setTimeout(function() {
            if ( $this.val().length >= parseInt($this.attr("maxlength"),10) )
                $this.next("input").focus();
        },0);
    });

When I combine script given above with Mottie Keyboard, it doesn't work.


Solution

  • I think you also opened the issue in the repository?

    To summarize my response there, use the change callback with the switchInput API function to accomplish what you need (demo):

    HTML (example)

    <input type="text" /> <!-- max len = 3 -->
    <input type="text" /> <!-- max len = 3 -->
    <input class="last" type="text" /> <!-- max len = 4 -->
    

    Script

    $(function() {
      $("input").keyboard({
        position: {
          // position under center input
          of: $("input:eq(1)"),
          // move down 12px; not sure why it doesn't line up
          my: 'center top+12',
          at: 'center top'
        },
        enterNavigation: true,
        maxLength: 4,
        layout: 'num',
        autoAccept: true,
        usePreview: false,
        change: function(e, keyboard, el) {
          var len = keyboard.$el.hasClass("last") ? 4 : 3;
          if (keyboard.$el.val().length >= len) {
            // switchInput( goToNext, isAccepted );
            keyboard.switchInput(true, true);
          } else if (keyboard.$el.val() === "" && keyboard.last.key === "bksp") {
            // go to previous if user hits backspace on an empty input
            keyboard.switchInput(false, true);
          }
        }
      });
    });