Click here to Skip to main content
15,886,199 members
Articles / Web Development / HTML
Alternative
Tip/Trick

Text box to accept only number

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
28 Apr 2011CPOL 11.7K   2   4
I have created a jQuery code to achieve this/*User Options --allowHex:Allow hexadecimal number default falseallowNeg:Allow negative default falseonlyInteger:did not allow decimal default true*/$(function () { var mergedOptions = {}; var common = { allowHex:...
I have created a jQuery code to achieve this

Java
/*
User Options --
allowHex:Allow hexadecimal number default false
allowNeg:Allow negative default false
onlyInteger:did not allow decimal default true
*/
$(function () {
    var mergedOptions = {};
    var common = {
        allowHex: false,
        allowNeg: false,
        onlyInteger: false
    };
});
var normalizeValue = function (val) {
    switch (val) {
        case 'undefined':
            val = undefined;
            break;
        case 'null':
            val = null;
            break;
        case 'true':
            val = true;
            break;
        case 'false':
            val = false;
            break;
        default:
            var nf = parseFloat(val);
            if (val == nf) {
                val = nf;
            }
    }
    return val;
};
$.fn.numericbox = function (userOptions) {
    return this.each(function () {
        $(this).keydown(function (e) {
            var key = e.charCode || e.keyCode || 0;
            var val = e.currentTarget.value;
            var options = new $.fn.numericbox.options(this, userOptions);
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            if (key == 45 && options.get('allowNeg') && val.indexOf('-') < 0) {
                e.currentTarget.value = "-" + e.currentTarget.value;
            }
           return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key == 190 && !options.get('onlyInteger') && val.indexOf('.') < 0) ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (((key >= 97 && key <= 102) || (key >= 65 && key <= 70)) && options.get('allowHex'))
                ); 
        })
    })
};
$.fn.numericbox.options = function (tag, userOptions) {
    this.userOptions = userOptions = userOptions || {};
    this.mergedOptions= $.extend({}, this.common, userOptions);
};
$.fn.numericbox.options.prototype.get = function (key) {
    return normalizeValue(this.mergedOptions[key]);
};


use this in any place like this
Java
$(document).ready(function () {
           $(".numeric").numericbox({ onlyInteger: true, allowNeg: true });
       });


this will make all the element (having css class numeric) to accept only complete either -ve or not, if you make alloqNeg:false then this will accept unsigned numbers only. You can use other jQuery selectors too.

or you can directly call this as a function on keydown event.

this Code is creating a function which add a keydown handler on every element calling this and in that code is checking is the key is printable or not based upon option passed by user.

This is handling negative or +ve no, decimal and Int no, Dec and Hex formats.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
• An Architect, developer, trainer, and student
• 10 years of experience in Architecture and Development of enterprise applications
• Extensive knowledge in designing and developing Web-based enterprise applications using open source and Microsoft Technologies
• Extensive experience in Angular, AngularJS, ReactJs, NodeJs, JavaScript, ASP.Net, C#, CSS, HTML

Comments and Discussions

 
QuestionHow to avoid Special Char like !@#$ Pin
Rajamohan.Rajendran8-Jul-14 21:13
Rajamohan.Rajendran8-Jul-14 21:13 
GeneralMy vote of 5 Pin
pankajupadhyay298-Feb-13 7:49
professionalpankajupadhyay298-Feb-13 7:49 
GeneralVery nicely explained Pin
Member 798302023-Jan-12 21:14
Member 798302023-Jan-12 21:14 
GeneralGood one. Pin
Prasanta_Prince28-Apr-11 3:26
Prasanta_Prince28-Apr-11 3:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.