20

i wrote few line to accept only numeric character but my script is not working. when i type any alphabet then it is getting inserted into textbox which i do not want. i want that textbox should accept only numeric value and "." point for decimal. here is my script. just tell me what is wrong there.

 $().ready(function () {
        $("input[id*='txtQty']").keyup(function (event) {
            var flag = false;

            if (event.shiftKey == true) {
                event.preventDefault();
            }
            // Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
            if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
                // Allow normal operation
                flag = true;
            } else {
                // Prevent the rest
                event.preventDefault();
            }

            if (flag) {

            }
        });
    });

if possible please give me script which will enable my textbox only numeric and decimal number. thanks

here is my full script. the problem is it is taking dot "." which i dont want.

        $().ready(function () {
        $("input[id*='txtQty']").keydown(function (event) {
            var flag = true;

            if (event.shiftKey == true) {
                event.preventDefault();
                flag = false;
            }

            if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

            } else {
                event.preventDefault();
                flag = false;
            }

            if (flag) {
                if (jQuery.trim(this.value) != "") {
                    if (IsNumeric(jQuery.trim(this.value)) == true) {
                        var Symbol = $("span[id*='lblPrice']").text().trim().substring(1, 0);
                        var oldprice = $("input[id*='txtHiddenPrice']").val();
                        var newprice = Math.round((oldprice * this.value), 2);
                        $("span[id*='lblPrice']").text(Symbol + newprice);
                        UpdateCart($(this).closest('tr').find("input[id*='txtItemId']").val(), $(this).closest('tr').find("input[id*='txtProductId']").val(), this.value);
                    }
                }
            }
        });
    });

so tell me what i need to change in my code as a result it should not take decimal value. another important thing i attach keydown() event with wild card system because my page may have many textbox with name end like txtQty.

 $("input[id*='txtQty']").keyup(function (event) {

so please help me. thanks

Thomas
  • 33,544
  • 126
  • 357
  • 626
  • Possible duplicate of [How to allow only numeric (0-9) in HTML inputbox using jQuery?](https://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – emkey08 Jul 18 '19 at 08:22

13 Answers13

48

You cant use e.preventDefault() it on the keyup event. Change it to keydown.

$(function () {
    $("input[id*='txtQty']").keydown(function (event) {


        if (event.shiftKey == true) {
            event.preventDefault();
        }

        if ((event.keyCode >= 48 && event.keyCode <= 57) || 
            (event.keyCode >= 96 && event.keyCode <= 105) || 
            event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 ||
            event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

        } else {
            event.preventDefault();
        }

        if($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
            event.preventDefault(); 
        //if a decimal has been added, disable the "."-button

    });
});​

Fiddle

Johan
  • 35,120
  • 54
  • 178
  • 293
  • still getting problem....please have look at edited part of my code. i use ur code but it still taking deciaml which i dont want. please tell me what i need to rectify. thanks – Thomas Oct 11 '12 at 09:32
  • @Thomas I thought you wanted to allow 1 "dot"? Or shouldnt it be allowed at all? – Johan Oct 11 '12 at 10:55
  • @Thomas then remove the check if its more than one dot: `$(this).val().indexOf('.') !== -1 &&` – Johan Oct 11 '12 at 19:14
  • 5
    I know this is an old post, but it's obviously still helpful because it helped me! Anyway, you haven't included the keypad's decimal, keyCode 110. – JB06 Dec 22 '14 at 20:40
  • Copy & paste by context menu of other characters will work :-( – mstrd308 Jan 16 '20 at 12:28
21

You could remove the non numeric char when keyup.

$("#txtQty").keyup(function() {
    var $this = $(this);
    $this.val($this.val().replace(/[^\d.]/g, ''));        
});​

The demo.

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • still getting problem....please have look at edited part of my code. i use ur code but it still taking deciaml which i dont want. please tell me what i need to rectify. thanks – Thomas Oct 11 '12 at 09:32
  • 2
    allows "10.547.547" . It should not be multiple "." for decimal. Isn't it? – Chandan Kumar Feb 23 '18 at 11:30
5

Create a numbers-only class and add it to your element

This will accept:
- backspace
- delete
- numbers
- one decimal

$(".numbers-only").keypress(function (e) {
    if(e.which == 46){
        if($(this).val().indexOf('.') != -1) {
            return false;
        }
    }

    if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
        return false;
    }
});
mpalencia
  • 5,481
  • 4
  • 45
  • 59
2

Preventing non-numeric numbers

        $(".number").on('keypress', function (e) {
            return e.metaKey || e.which <= 0 || e.which == 8 || e.which == 46 || /[0-9]/.test(String.fromCharCode(e.which));
            //      cmd/ctrl ||  arrow keys  ||   delete key ||   dot key     || numbers
        });
1

This solution only apply if you didn't include decimal number or only number from 0-9

$("#number").keypress(function( event ){
    var key = event.which;

    if( ! ( key >= 48 && key <= 57 ) )
        event.preventDefault();
});

you can view the running sample here http://jsfiddle.net/yghD3/6/

Ryan S
  • 6,076
  • 1
  • 20
  • 14
1
$('.number').keypress(function(event) {
  if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
  }
});
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
1

My solution accept Copy&Paste and save the position of the caret. It's used for cost of products so allows positive decimal values only. Can be refactor very easy to allow negative or just integer digits.

$(function () {
    $("input.only-positive-decimal").bind("change keyup input", function () {
            var position = this.selectionStart - 1;
                //remove all but number and .
                var fixed = this.value.replace(/[^0-9\.]/g, '');
                if (fixed.charAt(0) === '.')                  //can't start with .
                    fixed = fixed.slice(1);

                var pos = fixed.indexOf(".") + 1;
                if (pos >= 0)               //avoid more than one .
                    fixed = fixed.substr(0, pos) + fixed.slice(pos).replace('.', '');

                if (this.value !== fixed) {
                    this.value = fixed;
                    this.selectionStart = position;
                    this.selectionEnd = position;
                }
    });
});

Put on the html page:

<input type="text" class="only-positive-decimal" />
Carlos Toledo
  • 2,519
  • 23
  • 23
0

You could try http://www.texotela.co.uk/code/jquery/numeric/

This thread mentions the same plugin along with a bunch of other things you could try.

Community
  • 1
  • 1
boz
  • 4,891
  • 5
  • 41
  • 68
0
//This will let you enter numbers only and the decimal point ones.

$(window).load(function(){
$('.number').keypress(function(event) {
  if(event.which < 46 || event.which >= 58 || event.which == 47) {
    event.preventDefault();
  }

  if(event.which == 46 && $(this).val().indexOf('.') != -1) {
    this.value = '' ;
  }  
});
});
Steve
  • 1
  • 1
0

It will allow only 1 to 9 numbers and decimal. If other characters are being inserted, it will replace those digits.

<script>
  $("input[id*='txtQty']").keydown(function () {
    var txtQty = $(this).val().replace(/[^0-9\.]/g,'');
    $(this).val(txtQty);
  });
</script>

Check in fiddle.

Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
0

Try this code

$('#from-amount1').keypress(function(event) {
//alert(event.which == 8);
//alert(event.which);
    if((event.which > 47 && event.which < 58) || (event.which == 46 || event.which == 8))
    {
      // your condition
    }
    else
    {
    event.preventDefault();
    }
}).on('paste', function(event) {
    event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="text" value="" id="from-amount1"/>
karthik E
  • 92
  • 6
0
element.keypress(function (e) { 
    var charCode = (e.which) ? e.which : event.keyCode;
    var dec=0;

    dec = (this.value.match(/[.]/g) || [] ).length;

    if(dec===1 && e.key=='.')
        return false;

    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=46)
        return false;

});
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
0

1 Allows first character dot 2 Deny more than one dot 3 Allows both dot keys

in your HTML

<input class="number" type="number" log="" id="yourId" log="" />

$('#yourId').keypress(KeyPressOnlyDecimals);


function KeyPressOnlyDecimals (event) {

   if (event.which != 13)
        {
                let cId = $(window.getSelection().anchorNode).find('input')[0].id;
                let tId = $(event.currentTarget).attr('id');
                let sel = window.getSelection().toString();

                if (((event.which != 46  ) || ($(this).val().indexOf('.') != -1  && ($(event.currentTarget).val().length > 0 &&  ((cId != tId) || (cId === tId && (sel == null || sel.length == 0)))))) && (event.which < 48 || event.which > 57)) {
                    event.preventDefault();
                }
                $(event.currentTarget).on('paste', function(event) {
                    event.preventDefault();
                });
                var currentVal = $(event.currentTarget).val();

                let log =   $(event.currentTarget).attr('log');
                var count = log.split('.').length;
                if (count == 2 && event.which == 46 && sel != currentVal)
                {
                    event.preventDefault();
                }

                if (count >= 2)
                {

                    if (cId === tId && sel.length > 0)
                    {
                        var replaced = currentVal.replace(new RegExp(sel, 'g'), event.key);

                    }

                    if (count > 2 && $(event.currentTarget).val().length > 0 &&  ((cId != tId) || (cId === tId && (sel == null  || sel.length == 0) ))) 
                    {
                        event.preventDefault();
                    }

                }
                else
                {
                    if(event.which == 46)
                        $(event.currentTarget).attr('log',event.key);
                }

                console.log($(event.currentTarget).attr('log'));

        }
  }
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98