UnKnown UnKnown - 1 month ago 9
jQuery Question

How to put default value to zero when a input number is removed using backspace or using delete button?

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/

Answer

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.

Comments