How to lock cursor drive in Masked input?

Asked

Viewed 438 times

5

I’m using the plugin jQuery Masked Input.

<input name="dueDate" class="form-control input-mask-date" type="text" placeholder="Data de Vencimento" data-parsley-trigger="keyup" required="">

And I activate the Masked input through the class javascript.

$(".input-mask-date").mask("99/99/9999");

However, I can by clicking on the corner, stick around with the cursor in the last character of the mask.

How can I block this? Or how to always return the cursor to the first character when clicking?

Print do Masked Input

1 answer

4


I found a solution using jQuery quite interesting in the Soen that is not a property of Masked input plugin, but solve your problem:

$.fn.selectRange = function(start, end) {
    if(end === undefined) {
        end = start;
    }
    return this.each(function() {
        if('selectionStart' in this) {
            this.selectionStart = start;
            this.selectionEnd = end;
        } else if(this.setSelectionRange) {
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

You can use it as follows:

$(".input-mask-date").click(function() {
  $(".input-mask-date").selectRange(0);
});

Whenever the event of click is triggered, the cursor is positioned at the beginning of the input.

I created a Jsfiddle with an example.

  • 1

    So far it has solved the problem better.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.