I am trying to add auto slash in date field. I want the date format as yyyy/mm/dd
one keyup I want to add the slash automatically and after date(last number) it should not allow to type the number.
I want this function in pure javascript.
Here is my sample code.
var date = document.getElementById('date');
function checkValue(str, max) {
if (str.charAt(0) !== '0' || str == '00') {
var num = parseInt(str);
if (isNaN(num) || num <= 0 || num > max) num = 1;
str = num > parseInt(max.toString().charAt(0))
&& num.toString().length == 1 ? '0' + num : num.toString();
};
return str;
};
date.addEventListener('input', function(e)
{
this.type = 'text';
var input = this.value;
if (/\D\/$/.test(input)) input = input.substr(0, input.length - 3);
var values = input.split('/').map(function(v) {
return v.replace(/\D/g, '')
});
if (values[0]) values[0] = checkValue(values[0], 12);
if (values[1]) values[1] = checkValue(values[1], 31);
var output = values.map(function(v, i) {
return v.length == 2 && i < 2 ? v + ' / ' : v;
});
this.value = output.join('').substr(0, 14);
});
<input type="text" id="date">
In the above code the date format is as mm/dd/yyyy. I want this to change it to yyyy/mm/dd.
In suggested question it is simply printing the date. I want it to be done during onkey up function