Home » Javascript

JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters)

This JavaScript function will be used to restrict alphabets and special characters in Textbox , only numbers, delete, arrow keys and backspace will be allowed.

JavaScript Code Snippet - Allow Numbers in TextBox, Restrict Alphabets and Special Characters

JavaScript function

<script type="text/javascript">
	/*code: 48-57 Numbers
	  8  - Backspace,
	  35 - home key, 36 - End key
	  37-40: Arrow keys, 46 - Delete key*/
	function restrictAlphabets(e){
		var x=e.which||e.keycode;
		if((x>=48 && x<=57) || x==8 ||
			(x>=35 && x<=40)|| x==46)
			return true;
		else
			return false;
	}
</script>

HTML Source Code with JavaScript

<!--JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).-->
<html>
	<head>
		<title>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</title>
		<script type="text/javascript">
			/*code: 48-57 Numbers
			  8  - Backspace,
			  35 - home key, 36 - End key
			  37-40: Arrow keys, 46 - Delete key*/
			function restrictAlphabets(e){
				var x=e.which||e.keycode;
				if((x>=48 && x<=57) || x==8 ||
					(x>=35 && x<=40)|| x==46)
					return true;
				else
					return false;
			}
		</script>
	</head>
<body style="text-align: center;">
	<h1>JavaScript - Allow only numbers in TextBox (Restrict Alphabets and Special Characters).</h1>
	<big>Enter numbers only: </big>
	<input type="text" onkeypress='return restrictAlphabets(event)'/>
</body>

</html>

Result

allow only numbers in textbox javascript, javascript to restrict alphabets in textbox





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.