jQuery only digits in input

I want only numbers in my input. I can't change type of input to "number". So I have this code.

Number : <input type="text" name="quantity" id="quantity" />
<script>

$(document).ready(function() {


    $("#quantity").off("keyup").on("keyup", function(e) {
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }

        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 || 
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }

    });

});

And it's not works but if i change selector to $("#quantity").off("keyup").on("keyup", function(e) { It works. I haven't change the first selector

Answers:

Answer

try like this,

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

$("document").ready(function(){
 $("input").keyup(function(event){
    var input = $(this).val();
     if(!isNumber(input)){

        $(this).val(input.substring(0, input .length-1));
    }
  });
 });

Demo

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.