Javascript JQuery 函数只允许文本框中的字母不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38632792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery function to allow only alphabets in textbox not working
提问by Ajmal Razeel
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.
我使用以下 JQuery 函数来限制用户在文本框中写入数值。该代码工作正常,但问题是它也限制用户使用其他字符,如句号(.)、逗号(、)、$、@ 和其他符号。它也不允许用户使用复制和过去的。我只想限制用户写入数值或数字,但应该允许用户使用其他字符。
$(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();
}
}
});
});
回答by Timothy Kruger
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>
回答by Ajeet
$('.txtOnly').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else
{
e.preventDefault();
$('.error').show();
$('.error').text('Please Enter Alphabate');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="error"></p>
<input class="txtOnly" type="text">
回答by Parvez Rahaman
You could do using regex /[^a-z]/g
你可以使用正则表达式 /[^a-z]/g
$('.txtOnly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="lorem" class="txtOnly">
回答by niyasc
You may use following code snippet to prevent users from entering numeric input. It will check for each keydown
event and prevent any subsequent action if numeric value is provided.
您可以使用以下代码片段来防止用户输入数字。keydown
如果提供了数值,它将检查每个事件并阻止任何后续操作。
$('.txtOnly').bind('keydown', function(event) {
var key = event.which;
if (key >=48 && key <= 57) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="txtOnly">