3

I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user. Any suggestion for optimized and short javascript code?

fawad
  • 1,323
  • 11
  • 31
  • 50
  • 1
    Posible duplicate of : http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844#1830844 – Upendra Chaudhari Sep 17 '11 at 12:13
  • Possible duplicate of [Validate decimal numbers in JavaScript - IsNumeric()](https://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric) – Crono Jul 09 '18 at 14:10

9 Answers9

7
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

from here

Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
5

use following code

function numericFilter(txb) {
   txb.value = txb.value.replace(/[^\0-9]/ig, "");
}

call it in on key up

<input type="text" onKeyUp="numericFilter(this);" />
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86
  • 3
    For the love of god (and a professional feeling site), don't use `onkeyup`. See http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript. – Andy E Sep 17 '11 at 12:14
  • here have to use `onkeyup` because it will replace the current text after type. if you use other method like preventing the values `onkeydown` need to manually handle delete and backspace keys – Chamika Sandamal Mar 29 '13 at 11:30
  • totally agree with @AndyE. `onkeyup` is really suck especially if user simply paste the value using mouse click – Baby Dec 10 '13 at 02:55
  • @AndyE 's link is dead but he and Baby are right. Don't. Use. Keyup. – Crono Jul 09 '18 at 14:13
2

Here is a solution which blocks all non numeric input from being entered into the text-field.

html

<input type="text" id="numbersOnly" />

javascript

var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
    var k = e.which;
    /* numeric inputs can come from the keypad or the numeric row at the top */
    if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
        e.preventDefault();
        return false;
    }
};​
rlemon
  • 17,518
  • 14
  • 92
  • 123
2

Please note that, you should allow "system" key as well

    $(element).keydown(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which), value;
    if (isSysKey(code) || code === 8 || code === 46) {
        return true;
    }

    if (e.shiftKey || e.altKey || e.ctrlKey) {
        return ;
    }

    if (code >= 48 && code <= 57) {
        return true;
    }

    if (code >= 96 && code <= 105) {
        return true;
    }

    return false;
});

function isSysKey(code) {
    if (code === 40 || code === 38 ||
            code === 13 || code === 39 || code === 27 ||
            code === 35 ||
            code === 36 || code === 37 || code === 38 ||
            code === 16 || code === 17 || code === 18 ||
            code === 20 || code === 37 || code === 9 ||
            (code >= 112 && code <= 123)) {
        return true;
    }

    return false;
}
thangcao
  • 1,819
  • 1
  • 13
  • 14
2

// Solution to enter only numeric value in text box

$('#num_of_emp').keyup(function () { 
    this.value = this.value.replace(/[^0-9.]/g,'');
});

for an input box such as :

<input type='text' name='number_of_employee' id='num_of_emp' />

asprin
  • 9,579
  • 12
  • 66
  • 119
1

@Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.

For safer side, use this:

$("#testInput").keypress(function(event){

instead of:

$("#testInput").keyup(function(event){

I hope this will help for someone.

Nadeem
  • 419
  • 4
  • 13
0

Javascript For only numeric value in textbox ::

<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> 


    <!--Only Numeric value in Textbox Script -->
        <script type="text/javascript">
            function onlyNos(e, t) {
                try {
                    if (window.event) {
                        var charCode = window.event.keyCode;
                    }
                    else if (e) {
                        var charCode = e.which;
                    }
                    else { return true; }
                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                        return false;
                    }
                    return true;
                }
                catch (err) {
                    alert(err.Description);
                }
            }
        </script>
        <!--Only Numeric value in Textbox Script -->
Code
  • 679
  • 5
  • 9
  • Hi. While your code may solve the question, please add some clarification to what the code does. Specifically, what does it do that is different from the previous answers? – ItsPete Feb 19 '19 at 05:34
0

or

function isNumber(n){
  return (parseFloat(n) == n);
}

http://jsfiddle.net/Vj2Kk/2/

Shane
  • 4,921
  • 5
  • 37
  • 53
0

This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.

HTML:

<form>
    <input type="text" id="txt" />
</form>

JS:

(function(a) {
    a.onkeypress = function(e) {
        if (e.keyCode >= 49 && e.keyCode <= 57) {}
        else {
            if (e.keyCode >= 97 && e.keyCode <= 122) {
                alert('Error');
                // return false;
            } else return false;
        }
    };
})($('txt'));

function $(id) {
    return document.getElementById(id);
}

For a result: http://jsfiddle.net/uUc22/

Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.

David G
  • 94,763
  • 41
  • 167
  • 253
  • Why in the world would you do (or recommend) something like that? Even listing all number from 0 .. 9 and checking against them would be a better solution. Nobody will be able to figure out what you are doing, by just reading this peace of code. And really, he just wants to know, if he has a number of not. – philgiese Sep 17 '11 at 14:03
  • He said he wants "only" numeric characters in the field, not just to know if they are typed; and if otherwise (alphabetic) then warn the user. I know the `.keyCode` part can throw people off but I needed a faster way to do this. – David G Sep 17 '11 at 14:53
  • Did the OP ask for a jquery solution? – KooiInc Sep 17 '11 at 15:13
  • Did I use jQuery? Or make the $ function myself? – David G Sep 17 '11 at 16:33