2

I have a input number which should always a default value as zero

Incase the user has done a backspace or delete button and removed the value how can i put default value zero as back

This is my code

$(document).ready(function () {
  $(".numbersonly").keypress(function (e) {
     if(this.value.length=='0')
     {
             $(this).val('0');
     return false;
     }

     if(this.value.length==2) return false;

     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
        $(this).val('0')
               return false;
    }
   });
}); 

This is my fiddle

http://jsfiddle.net/HkEuf/10265/

Pawan
  • 31,545
  • 102
  • 256
  • 434

2 Answers2

2

You can always put back the 0 if a user leaves the input box and there is no value in it like this:

$(document).ready(function() {
  $(".numbersonly").keyup(function(e) {

    if (this.value.length > 2) {
      $("#errmsg").html("Digits Only").show().fadeOut("slow");
      $(this).val($(this).val().substr(0, this.value.length - 1));
      return false;
    }

  });
  $(".numbersonly").blur(function() {
    console.log("blur")
    if ($(this).val() == "") {
      $(this).val('0')
    }
  })
});

The blur function checks the input box after the user clicks outside of it.

Zorken17
  • 1,896
  • 1
  • 10
  • 16
1

Use keyup rather than keypress, it solves your problem.

The keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed.

Check this answer: https://stackoverflow.com/a/11030750/2611451

The events are for completely different purposes. Use keyup and keydown for identifying physical keys and keypress for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two. In particular, keyCode on keypress events is usually redundant and shouldn't be used (except in older IE, but see the linked document below for more on that); for printable keypresses it's usually the same as which and charCode, although there is some variation between browsers.

Community
  • 1
  • 1
KAD
  • 10,972
  • 4
  • 31
  • 73