I am trying to format my textfield where user will enter his date of birth.
Currently when user starts typing the 3rd character, i am adding "/".
But i need to add "/" when user types the 2nd character.
Please find my code below,
$.dobTextfield.addEventListener("change", function (event) {
var dobValue = $.dobTextfield.value;
dobValue = dobValue.replace(/\//g, '');
var newVal = '';
var sizes = [2, 2, 4];
for (var i in sizes) {
if (dobValue.length > sizes[i]) {
newVal += dobValue.substr(0, sizes[i]) + '/';
dobValue = dobValue.substr(sizes[i]);
}
else
break;
}
newVal += dobValue;
$.dobTextfield.value = newVal;
});
Recommendation: Use a Date Picker
I would recommend that you replace your textfield with a label (possibly styled to look like a textfield if that is important).
I would then add a click event to the label which would display a date picker. Date Picker Docs
You could the update the label's value based on date picker's value.
Solution to your existing code
var oldValue;
$.dobTextfield.addEventListener("change", function (event) {
var dobValue = $.dobTextfield.value;
// this checks to see if the user has removed a slash bu hitting backspace
// without this the user would not be able to delete a back space
if (oldValue == dobValue + "/") {
return;
}
var newVal = '';
var sizes = [2, 2, 4];
if (dobValue.length == 2 || dobValue.length == 5) {
dobValue += "/";
}
$.dobTextfield.value = dobValue;
oldValue = $.dobTextfield.value;
});
This will enter the slash when the user types the 2nd character and will also allow the user to delete a slash using the backspace if they need to edit the date.
Other considerations
Your current textfield allows the user to enter an invalid date. For example the user could enter a date such as 60/99/2018. Using a date picker would remove the need for such validation.