![](/img/trans.png)
[英]JQuery to allow only alphabets, numeric and forward slash in TextBox
[英]JQuery function to allow only alphabets in textbox not working
我使用以下JQuery函數來限制用戶在文本框中寫入數字值。 該代碼可以正常工作,但問題在於它還限制了用戶使用其他字符,例如句號(。),逗號(,),$,@和其他符號。它也不允許用戶使用copy和過去。 我只想限制用戶寫數字值或數字,但應該允許用戶使用其他字符。
$(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();
}
}
});
});
希望這可以幫助:
<!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>
您可以使用正則表達式/[^az]/g
$('.txtOnly').bind('keyup blur',function(){ var node = $(this); node.val(node.val().replace(/[^az]/g,'') ); } );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="lorem" class="txtOnly">
$('.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">
您可以使用以下代碼段阻止用戶輸入數字輸入。 如果提供了數值,它將檢查每個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">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.