Automatically add Slash / character to Date <input> field by jquery

(I find a few questions, but no answer, so I asked a question)
How to add auto Slash / symbol to the <input> field when entering / enter Date?
Example: when type 02 or date, month, year, jquery will automatically add / character after 2 digits in the input field, for example, 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 using jquery or JS?

0
source share
3 answers

Something like this will work. Also check out the included JSFiddle.

 $( 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 similar to this jQuery: https://github.com/RobinHerbots/jquery.inputmask

+1
source

Attach the onkeydown event handler to your <input> field, and whenever the input field is 2 or 5, add "/" to it.

script: - https://jsfiddle.net/nuh4dy6j/ `

 var input = document.querySelector('input'); input.addEventListener('keydown', ev => { var ipLength = ev.target.value.length; if(ipLength ===2 || ipLength ===5) { ev.target.value += '/'; } }); 
+1
source

You can do it try

 $(document).ready(function() { $("#inputDate").keyup(function(){ if ($(this).val().length == 2){ $(this).val($(this).val() + "/"); }else if ($(this).val().length == 5){ $(this).val($(this).val() + "/"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="inputDate" type="text" /> 
+1
source

Source: https://habr.com/ru/post/946380/


All Articles