I\'m trying to add functionality to input date fields so as when the users enters in digits, slashes \"/\" get automatically added.
So suppose I have the following
Handles backspace, delete, paste, long press.
let $jqDate = $('.date-slashes');
$jqDate.bind('keyup', function(ev) {
if (ev.which !== 8) {
let input = $jqDate.val();
let out = input.replace(/\D/g, '');
let len = out.length;
if (len > 1 && len < 4) {
out = out.substring(0, 2) + '/' + out.substring(2, 3);
} else if (len >= 4) {
out = out.substring(0, 2) + '/' + out.substring(2, 4) + '/' + out.substring(4, len);
out = out.substring(0, 10)
}
$jqDate.val(out)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<input name="dob" class="date-slashes" type="tel" maxlength="10" placeholder="mm/dd/yyyy">
Here is an updated Jquery version. Just change #txtDate with your field ID
$(document).ready(function() {
$("#txtDate").keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});
});
Source: https://forum.jquery.com/topic/auto-slash-in-date-field
// This solution also handle the delete and backspace keys:
jQuery('input[name="dateofbirth"]').bind('keyup',function(event){
var key = event.keyCode || event.charCode;
if (key == 8 || key == 46) return false;
var strokes = $(this).val().length;
if (strokes === 2 || strokes === 5){
var thisVal = $(this).val();
thisVal += '/';
$(this).val(thisVal);
}
// if someone deletes the first slash and then types a number this handles it
if (strokes>=3 && strokes<5){
var thisVal = $(this).val();
if (thisVal.charAt(2) !='/'){
var txt1 = thisVal.slice(0, 2) + "/" + thisVal.slice(2);
$(this).val(txt1);
}
}
// if someone deletes the second slash and then types a number this handles it
if (strokes>=6){
var thisVal = $(this).val();
if (thisVal.charAt(5) !='/'){
var txt2 = thisVal.slice(0, 5) + "/" + thisVal.slice(5);
$(this).val(txt2);
}
}
});
Try to use this plugin : http://digitalbush.com/projects/masked-input-plugin/ It works with jquery.
My regex solution for React:
// add auto "/" for date, i.e. MM/YY
handleExpInput(e) {
// ignore invalid input
if (!/^\d{0,2}\/?\d{0,2}$/.test(e.target.value)) {
return;
}
let input = e.target.value;
if (/^\d{3,}$/.test(input)) {
input = input.match(new RegExp('.{1,2}', 'g')).join('/');
}
this.setState({
expDateShow: input,
});
}
If you're looking for pure js version of @Chris's answer
var newInput = document.getElementById("theDate");
newInput.addEventListener('keydown', function( e ){
if(e.which !== 8) {
var numChars = e.target.value.length;
if(numChars === 2 || numChars === 5){
var thisVal = e.target.value;
thisVal += '/';
e.target.value = thisVal;
}
}
});
And HTML section might be(if necessary):
<input type="text" name="theDate" id="birthdate" maxlength="10"/>