I use the following JQuery function to restrict users from writing numeric values in the textbox. The code works fine but the problem is that it also restrict users from using other characters like full stop(.), comma(,), $, @ and other signs..It also does not allow users to use the options of copy and past. I only want to restrict the users from writing numeric values or numbers but the user should be allowed to use other characters.
$(function() {
$('.txtOnly').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});
To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.
_%+-]+@[a-z0-9. -]+\. [a-z]{2,3}$"> will restrict the allowed characters according that RegExp pattern (in this case: valid-looking email addresses). The title attribute will be used as a warning / notification when the user tries to submit the data not matching the requirement.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
Hope this helps:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
<input class="txtOnly" id="txtOnly" name="txtOnly" type="text" />
<script>
$( document ).ready(function() {
$( ".txtOnly" ).keypress(function(e) {
var key = e.keyCode;
if (key >= 48 && key <= 57) {
e.preventDefault();
}
});
});
</script>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With