Aariba Aariba - 3 months ago 27
HTML Question

Auto add Slash / symbol in Date <input> box by jquery

(I find several question but no answer, so i asked question)


How to add auto Slash / symbol in

<input>
box when input/type Date?


Example: when type 02 or any date, month, year number, jquery will auto add / symbol after 2 number in input box, like 02/12/2016


please Check jsfiddle example: https://jsfiddle.net/rjkdd9j6/

HTML:

<input type="text" id="your-id" value="dd/mm/yy">


Is there any simple solution by jquery or JS ?

Answer

Something like this will work. Check the attached JSFiddle too.

$( document ).ready(function() {
    $('#your-id').bind('keyup','keydown', function(event) {
    var inputLength = event.target.value.length;
    if(inputLength === 2 || inputLength === 5){
      var thisVal = event.target.value;
      thisVal += '/';
      $(event.target).val(thisVal);
    }
  })
});

https://jsfiddle.net/ahmedhawas7/rjkdd9j6/3/

You can also use an input mask library like this Jquery one: https://github.com/RobinHerbots/jquery.inputmask