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
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.