0

I am new to jQuery and little bit confused on how to get only numbers from 1 to 5 in an input box. The following is my code:

HTML

<div id="errmsg"></div>

<input type="text" id="number" maxlength="1"/>

SCRIPT

$(document).ready(function(e) {
$('#number').keydown(function(e){
if (e.which != 8 && e.which != 0 && (e.which < 49 || e.which > 53)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }

    else if (e.which == 48 || e.which < 48 || e.which > 53) {
        //display error message
        $("#errmsg").html("5 Only").show().fadeOut("slow");
               return false;
    }
})

})
</script>

When the user enters any amount in the input box, if he inputs any character then error message "Digits Only" will be shown. If he enters number more than 5 then error "only 5" message will be shown.

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
Kamal
  • 2,140
  • 8
  • 33
  • 61
  • possible duplicate of [How to allow only numeric (0-9) in HTML inputbox using jQuery?](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – Andreas Oct 10 '13 at 10:47
  • 2
    In this case maybe a `select` with 0..5 would be better / clearer for the user? – Raidri Oct 10 '13 at 10:47
  • thanks for advise but I need to use only input – Kamal Oct 10 '13 at 10:56

2 Answers2

1

Try This

$(document).ready(function() {
    $("#number").keydown(function(event) {
        console.log(event.keyCode);
        if ( $.inArray(event.keyCode,[49,50,51,52,53]) !== -1) 
        {
                 alert("allow");
        }
        else {
            alert("not allow");      
        }
    });
  });

FIDDLE

YashPatel
  • 295
  • 1
  • 2
  • 9
0

I appreciate you've already accepted an answer, but for what it's worth, I think this is a more user-friendly solution: JSFiddle

It handles control characters (such as Del, Backspace, Tab and Enter) and numbers entered through the numeric keypad. It also meets your requirement of having separate error messages for non-numeric characters and numbers > 5.

$(document).ready(function() {
    $("#number").on('keyup', function(event) {

        var entered = $(this).val(),
            content = parseInt(entered,10);

        if (entered !== '' && isNaN(content)) {

            $('#errorMsg').text('Digits only');
            $(this).val('');

        } else if (content > 5) {

            $('#errorMsg').text('Only 5');
            $(this).val('');

        } else {

            $('#errorMsg').text('Okay');

        }
    });
});

However, unlike the other solution, it doesn't prevent the user from entering invalid data, but will retrospective delete the character after it has been entered. This may or may not meet your expectations.

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41