最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Allow only Numbers in text box using jquery with out extra plugins - Stack Overflow

programmeradmin10浏览0评论

i wanted to Allow only Numbers in text box using jquery/javascript with out extra plugins

I have coded like :

if ( event.keyCode == 46 || event.keyCode == 8 || (event.keyCode >=48 && event.keyCode <=57)) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress           
            event.preventDefault();                   
        }

but it allows special characters like ! (Shift+1), @ (shift +2) etc.

can any body tell me the complete solution for this .. thanks in advance

i wanted to Allow only Numbers in text box using jquery/javascript with out extra plugins

I have coded like :

if ( event.keyCode == 46 || event.keyCode == 8 || (event.keyCode >=48 && event.keyCode <=57)) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress           
            event.preventDefault();                   
        }

but it allows special characters like ! (Shift+1), @ (shift +2) etc.

can any body tell me the complete solution for this .. thanks in advance

Share Improve this question asked Dec 26, 2011 at 11:41 srinisrini 3833 gold badges7 silver badges17 bronze badges
Add a comment  | 

7 Answers 7

Reset to default 4

This is unbreakable.

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});
<input type="text" onKeyUp="$(this).val($(this).val().replace(/[^\d]/ig, ''))" />

This textbox allows only numbers. Even other characters are entered get disappeared.

You can use the new html5 input type of 'number'. It will only take the number as inputs. But it depends on the browser which supports it or not.

<input type="number" />

you can also define the range of number as

<input type="number" min="1" max="10" />

I solved by using the below code snippet. thanks for the inputs and help

$('input[etype="Number"]').keydown(function(event) {

     if(event.shiftKey && ((event.keyCode >=48 && event.keyCode <=57) 
             || (event.keyCode >=186 &&  event.keyCode <=222))){
        // Ensure that it is a number and stop the Special chars
         event.preventDefault();
     }
     else if ((event.shiftKey || event.ctrlKey) && (event.keyCode > 34 && event.keyCode < 40)){     
          // let it happen, don't do anything
     }      
     else{
        // Allow only backspace , delete, numbers               
        if (event.keyCode == 9 || event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 39 ||event.keyCode == 37 
                || (event.keyCode >=48 && event.keyCode <=57)) {
            // let it happen, don't do anything
        }
        else {
           // Ensure that it is a number and stop the key press
                event.preventDefault();                   
        }
     }
    });

The solution below:

  • allows numerics on number pad as well as keyboard
  • does not allow ctrl,alt,shift key
  • allows tab key to navigate to next text box
  • allows back-space,delete,and arrow keys to move inside your textbox

It does this by checking, step by step, to see if the event matches certain criteria.

$(".onlyNumerics").keydown(function (event) {
    var num = event.keyCode;
    if ((num > 95 && num < 106) || (num > 36 && num < 41) || num == 9) {
        return;
    }
    if (event.shiftKey || event.ctrlKey || event.altKey) {
        event.preventDefault();
    } else if (num != 46 && num != 8) {
        if (isNaN(parseInt(String.fromCharCode(event.which)))) {
            event.preventDefault();
        }
    }
});

See this bellow Example. You can prevent not numerical values by using Regex.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
            function Numeric()
            {
                var field=document.iform.mob.value;            
                if (!field.match(/^[\-\+]?[\d\,]*\.?[\d]*$/))
                {
                    alert("Enter only Numerics");
                    return false;
                }
            }
        </script>
      </head>
      <body>
          <form name="iform" method="post">
              Add Your Mobile Number: <input type="text" name="mob" />
              <br/>
              <input type="submit" value="OK" onclick="return Numeric();" />
          </form>
      </body>
    </html>

I'll just add another sample to the list.

I have been using this in my projects for quite a while. The function is bind to keyup event of the input[type=text]

function handleInputKeyup(e) {

    // if you want to enforce a minimum value 
    // declare somewhere else if need be
    const DEFAULT_VALUE = 1 

    //don't do anything if the text is empty
    if ($(this).val().length > 0) {
        const currentValue = Number($(this).val())

        if (isNaN(currentValue)) {
            $(this).val(DEFAULT_VALUE);
            return;
        }

        if (currentValue <= 0) {
            $(this).val(DEFAULT_VALUE);
            return;
        }
    }

}
发布评论

评论列表(0)

  1. 暂无评论