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?

2

9 Answers 9

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

from here

Sign up to request clarification or add additional context in comments.

2 Comments

Why didn't you flag the question as a duplicate then?
this will privent backspace and delete
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);" />

4 Comments

For the love of god (and a professional feeling site), don't use onkeyup. See whattheheadsaid.com/2010/09/….
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
totally agree with @AndyE. onkeyup is really suck especially if user simply paste the value using mouse click
@AndyE 's link is dead but he and Baby are right. Don't. Use. Keyup.
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;
    }
};​

Comments

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

Comments

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

Comments

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.

Comments

0

or

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

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

Comments

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.

4 Comments

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.
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.
Did the OP ask for a jquery solution?
Did I use jQuery? Or make the $ function myself?
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 -->

1 Comment

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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.