1

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

5
  • I think you need keydown or keypress Commented Mar 7, 2014 at 17:00
  • Why can't you change the input type? If it's that you can't change the html then that's not an issue - you can change the input type with javascript. Commented Mar 7, 2014 at 17:01
  • Do you have another event handler which is interfering with keyup? Commented Mar 7, 2014 at 17:01
  • i used keydown, I will tested this lately, thnk u ;) Commented Mar 7, 2014 at 17:13
  • @AnoopJoshi, No I known that my code works with keyup. I just wondered why it didn't works with first selector Commented Mar 7, 2014 at 17:20

1 Answer 1

1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.