How to I add dots automatically while typing in jquery?

1.5k Views Asked by At

I have a form with a field of date in which the user has to type the digits and the dots will automatically format the value. Ex: user tipes 056, when he presssed on 6 a dot after 5 was added. I want to make it in format dd.mm.yyyy but since it is just text input I am working on right now I do not have to define these three atributes. My code so far:

    $(document).ready(function(){
        $('#date').keyup(function(event){
        if(event.which >= 37 && event.which <= 40){
           event.preventDefault();
    }
        var $this = $(this);
        var num = $this.val().replace(/,/gi, "").split("").reverse().join("");

        var num2 = RemoveRougeChar(num.replace(/(.{2})/g,"$1,").split("").reverse().join(""));

          console.log(num2)
          $this.val(num2);


        if(convertString.substring(0,4) == ".") {
            return convertString.substring(2, convertString.length)  }
            return convertString;}

When I type the first two digits a comma appears in front of the value, just after I type the third one the comma is moved. How can I write the code so that the comma is replaced by a dot and added twice: first after day digits and second after month digits?

1

There are 1 best solutions below

4
On BEST ANSWER

You can use script i wrote for this purpose:

var dateFormatter = function () {    
    if (!arguments) return;        
    this.dateInputFields = arguments;
    this.isFormatted = false;        

    (function ($) {
        $.fn.getCursorPosition = function () {            
            var input = this.get(0);
            if (!input) return; // No (input) element found
            if (document.selection) {
                // IE
                input.focus();
            }
            return 'selectionStart' in input ? input.selectionStart : '' ||
                Math.abs(document.selection.createRange().moveStart('character', -input.value.length));
        }
    })( jQuery );

    function setEvents() {        
        for (var i = 0; i < this.dateInputFields.length; i++) {
            $(this.dateInputFields[i]).keyup(function (e) {                
                if (e.keyCode == 8 || e.keyCode == 46) return;
                s = e.target.value;
                var caretPos = $(e.target).getCursorPosition();
                if (caretPos == 2) s.length > 2? e.target.value[3] = '.' : e.target.value += '.';
                if (caretPos == 5) s.length > 5 ? e.target.value[5] = '.' : e.target.value += '.';
                if (caretPos == 10) s.length > 10 ? e.target.value[11] = ' ' : e.target.value += ' ';
                if (caretPos == 13) s.length > 13 ? e.target.value[10] = ':' : e.target.value += ':';
            });
        }
        this.isFormatted = true;
    };

    setEvents();
};

Save this as dateFormatter.js

In your html connect it before(!) any other scripts except jquery. In other script, where you do all stuff just add line:

var dtFormat = dateFormatter($selector1, $selector2, etc);

Change $selector1 with your selector (in my case it was input id #changesDate). You can pass multiple 'selector' parameters.

Example : http://embed.plnkr.co/2ahM90nNlhgRH4yCD6Y2/preview