JavaScript – Enter Only Characters In Text Box

Title

JavaScript – Enter Only Characters In Text Box

Introduction

In this post we will see how we can use JavaScript code which allow user to enter only characters in Text Box in HTML. And I won’t be using any RegEx.

Have a look at below code.


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function validate(e) {

var code = (event.which) ? event.which : event.keyCode;
if ((code >= 65 && code <= 97) || (code >= 97 && code <= 122) || (code == 32)) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form name="form1">
<input type="text" id="val" onkeypress="return validate(event);" />
</form>
</body>
</html>

In this code I’ve used a JavaScript events, event.which and even.keyCode

<pre>var code = event.which;</pre>

Code contains the numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed.

<pre>var code = event.keyCode;</pre>

Code contains the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

<pre>if ((code >= 65 && code <= 97) || (code >= 97 && code <= 122) || (code == 32))</pre>

This piece of code matches the value contained in variable code with the ASCII values of lower and upper case alphabets and ASCII Code 32 is for space bar.


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar