JQUERY

How to Add Slash Automatically While Typing Date in Text-box

In this Blog, we give you a trick to add slash(/) automatically while user typing date in text element. you can do it with the help of simple Jquery events keyup and keydown.

Date Format: 09/09/2001

<script type="text/javascript">

jQuery("#date-filed-id").keydown(function(e){
	var dob = jQuery("#date-filed-id").val();
	
		// for back slash
		if (e.keyCode == 8) {
			return true;
		}
		
		if((dob.length == 2 || dob.length == 5) && e.keyCode != 191) {
			return false;
		}
		
		if(dob.length >= 10 || e.keyCode == 47) {
			return false;
		}
		if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105)) {
			return true;
		}
		else 
		{ return false;
		}
});

	jQuery("#date-filed-id").keyup(function(e){
		var dob = jQuery("#date-filed-id").val();
		
		if(e.keyCode == 8 && (dob.length == 2 || dob.length == 5) ) {
			return true;
		}
		if(dob.length == 2) {
			jQuery("#date-filed-id").val(dob+'/');
		}
		if(dob.length == 5) {
			jQuery("#date-filed-id").val(dob+'/');
		}
});
</script>
<html>
	<head>
		<title>Test Page</title>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	</head>
	<body>
		<div>
			<h1>Please enter Date of Birth</h1>
			<input type="text" id="date-filed-id" />
		</div>
	</body>
</html>

We have this blog is helpful for you. please leave comment if you have any queries.

Thank you):

Tagged , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *