Dom Adams
Dom Adams

Reputation: 281

Need to make input only take numbers

Hi I have an input box:

<input id="txtboxToFilter" type="text" placeholder="dd/mm/yyyy" />

Now I want it to only accept a date format, so if the user tries to enter a letter it doesn't let him...

I have tried this:

    $("#txtboxToFilter").keydown(function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) || 
         // Allow: home, end, left, right, down, up
        (e.keyCode >= 35 && e.keyCode <= 40)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

But it is not working...
any ideas?

Upvotes: 0

Views: 124

Answers (2)

HaveNoDisplayName
HaveNoDisplayName

Reputation: 8497

You can try this jquery code to input only digits, not characters.

DEMO:- http://jsfiddle.net/8z92v8yf/2/

 <input id="txtboxToFilter" type="text" placeholder="dd/mm/yyyy" />
  <span id="errmsg"></span> 

$(document).ready(function () {
  //called when key is pressed in textbox
  $("#txtboxToFilter").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 < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
});

Upvotes: 0

amtest
amtest

Reputation: 700

Only to accept the number, you can try this

$("#txtboxToFilter").forcenumeric();
$.fn.forcenumeric = function () {

         return this.each(function () {
             $(this).keydown(function (e) {
                 var key = e.which || e.keyCode;

                 if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                 // numbers   
                     key >= 48 && key <= 57 ||
                 // Numeric keypad
                     key >= 96 && key <= 105 ||
                 // Backspace and Tab and Enter
                    key == 8 || key == 9 || key == 13 ||
                 // Home and End
                    key == 35 || key == 36 ||
                 // left and right arrows
                    key == 37 || key == 39 ||
                 // Del and Ins
                    key == 46 || key == 45)
                     return true;

                 return false;
             });
         });
 };

Upvotes: 1

Related Questions