简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM