abcid d
abcid d

Reputation: 2947

Enter only numbers and "-" in textbox using jquery

I have a JQuery syntax to allow users enter only numbers in the text field. Live code

Then I need to write an extra code to allow users can enter "-" (hyphen) in the text box, but it doesn't work. Live code

Please help.

HTML

Number : <input type="text" name="quantity" id="quantity" />&nbsp;<span id="errmsg"></span>

CSS

#errmsg{color: red;}

JS

$(document).ready(function () {
  //called when key is pressed in textbox
  $("#quantity").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && e.which !=='-' && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

Upvotes: 1

Views: 4742

Answers (2)

Marco Bonelli
Marco Bonelli

Reputation: 69316

Using regExps is really, really easier! Use the regExp /[0-9\-]/g to check if the text contains only the characters you want, and if it doesn't show the error msg.

$(document).ready(function () {
    $("#quantity").keypress(function (e) {
        var text = this.value;
        if (text.match(/[0-9\-]/g).join('') != text) {
            $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
        }
    });
});

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

You can allow hyphens by adding String.fromCharCode(e.which) != '-' (charCode for -) into your condition:

if (e.which != 8 && e.which != 0 && String.fromCharCode(e.which) != '-' && (e.which < 48 || e.which > 57)) {
    ...
}

Demo (updated): http://jsfiddle.net/HkEuf/2669/

Upvotes: 2

Related Questions