jQuery函数仅允许文本框中的字母不起作用 [英] JQuery function to allow only alphabets in textbox not working

查看:73
本文介绍了jQuery函数仅允许文本框中的字母不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下JQuery函数来限制用户在文本框中写入数字值.该代码可以正常工作,但问题在于它还限制了用户使用其他字符,例如句号(.),逗号(,),$,@和其他符号.过去的.我只想限制用户写数字值或数字,但应该允许用户使用其他字符.

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();
      }
    }
  });
});

推荐答案

希望这会有所帮助:

<!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>

这篇关于jQuery函数仅允许文本框中的字母不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆