srini
srini

Reputation: 383

Allow only Numbers in text box using jquery with out extra plugins

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

Upvotes: 1

Views: 28204

Answers (7)

Whyashh
Whyashh

Reputation: 93

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

}

Upvotes: 0

Jonathan
Jonathan

Reputation: 9151

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

Upvotes: 4

maxatmin.com
maxatmin.com

Reputation: 51

<input type="text" onKeyUp="$(this).val($(this).val().replace(/[^\d]/ig, ''))" />

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

Upvotes: 3

Umesh K.
Umesh K.

Reputation: 311

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

Upvotes: 2

srini
srini

Reputation: 383

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

Upvotes: 2

Hearaman
Hearaman

Reputation: 8736

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>

Upvotes: 0

Talha
Talha

Reputation: 19282

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" />

Upvotes: 2

Related Questions