How to block cursor movement in masked input?

5

I'm using the jQuery Masked Input plugin.

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

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

However, I get to click on the corner, stay with the cursor on the last character of the mask.

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

    
asked by anonymous 13.06.2017 / 21:06

1 answer

4

I found a solution using jQuery quite interesting in SOen is not a property of the masked input plugin , but solves 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 click event fires, the cursor is positioned at the beginning of input .

I created a JSFiddle with an example.

    
13.06.2017 / 21:28