Custom Date of Birth Input Using JQuery
by Shubham Agrawal
HTML
<form>
<input type="text" id="dateofBirth" value="" required>
<input type="submit" value="Submit">
</form>
JavaScript
var cnt = 0;
$("#dateofBirth").focus(function() {
if ($(this).val() == "")
$(this).val("__/__/____");
});
$('#dateofBirth').keydown(function(event) {
if ((event.which >= 48 && event.which <= 57 && cnt < 8) || (event.which == 8)) {
ccc = [0, 1, 3, 4, 6, 7, 8, 9];
var vl = $("#dateofBirth").val();
var res = vl.split("");
if (event.which == 8) {
cnt--;
res[ccc[cnt]] = "_";
} else {
res[ccc[cnt]] = String.fromCharCode(event.which);
cnt++;
}
var myVar = "";
for (var i = 0; i < res.length; i++) {
myVar += res[i];
}
$('#dateofBirth').val(myVar);
}
event.preventDefault();
});