Charles L.
Charles L.

Reputation: 1970

jQuery format date on input

I'm trying to format a date as the user enters into the input field by assigning a class to it which is inside a function. I know its firing but something is quite right its throwing [object] in the input field. My end goal is as the user types it will throw a / after the first two characters and then another / after the next two: 01/01/2017

CODE:

    $(document).off('keydown', '.dateField');
    $(document).on('keydown', '.dateField', function(e){
        var start = this.selectionStart,
            end = this.selectionEnd;

            if($(this).val().replace(/[^\d]/g,"").length<$(this).val().length)
                end = end-1;

            $(this).val($(this).toString().substr(0,2)+"/"+$(this).toString().substr(2));

            this.setSelectionRange(start, end);
  }

UPDATED CODE:

$(document).on('keydown', '.dateField', function(e){

    $(this).attr('maxlength', '10');

    var key=String.fromCharCode(e.keyCode);

    if(!(key>=0&&key<=9)){
        $(this).val($(this).val().substr(0,$(this).val().length-1));
    }

    var value=$(this).val();

    if(value.length==2||value.length==5){
        $(this).val($(this).val()+'/');
    }

This is not preventing letters and symbols how do i add regex to prevent this problem. (super noob at egex)

Upvotes: 0

Views: 962

Answers (1)

Charles L.
Charles L.

Reputation: 1970

Final Code:

    $(document).off('keydown', '.dateField');
    $(document).on('keydown', '.dateField', function(e){

        $(this).attr('maxlength', '10');

        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
             // Allow: home, end, left, right, down, up
            (e.keyCode >= 35 && e.keyCode <= 40)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }

        var value=$(this).val();

        if(value.length==2||value.length==5){
            $(this).val($(this).val()+'/');
        }
}

Upvotes: 2

Related Questions