I'm trying to achieve in the input box user can enter only numbers and the date format should be YY/MM/DD.
In the following example I can enter only numbers using replace method.
I want to achieve using the same method when user keyup the numbers format should be YY/MM/DD.
Please drop a comment for more clarification
$(document).on("keyup", "input", function() {
$(this).val($(this).val().replace(/[^0-9\/]/g, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="YY/MM/DD">
Please follow this.
JS
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
$(document).ready(function() {
$("#datePicker").ForceNumericOnly();
$('#datePicker').keyup(function(){
let val = $(this).val()
if(val.length==2)
{
val = val+'/'
$(this).val(val)
}
else if (val.length==5)
{
val = val+'/'
$(this).val(val)
}
})
});
HTML
<input id="datePicker" type="text" maxlength="8">