Sora
Sora

Reputation: 2551

check if input is empty set to zero in javascript

When the user delete the value in input using the backspace the function work correctly but if he delete the value and set a new number like 1 the new value is deleted and set again to zero.

<input type="text" id="txtField" value="0" ></input>

$(document).ready(function() {

  $("#txtField").keyup(function() {

    var v = $(this).val();

    console.log(v)
    if (v == "") {
      console.log(v)
      setTimeout(function() {
        $("#txtField").val(0);
      }, 1000);

    }
  });
});

I don't know what is the problem in my code any help please?

jsFiddle: http://jsfiddle.net/2shadgtw/2/

Upvotes: 2

Views: 4441

Answers (5)

Shuvro
Shuvro

Reputation: 1499

The best way to do this would be using focusout() function. Try this

<input type="text" id="txtField" value="0" />

$("#txtField").focusout(function() {

var v = $(this).val();

console.log(v)
if (v == "") {
    $("#txtField").val(0);
}
});

It will set the value to zero on focus out if the field is empty.

JSFIDDLE EXAMPLE

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Don't use setTimeout. Instead try mapping with these three events:

$(document).ready(function() {
  $("#txtField").on("keyup change blur", function() {
    if ($(this).val().trim() == "")
      $(this).val(0);
  });
});

Fiddle: http://jsfiddle.net/5hm6e8hL/

Upvotes: 3

Danield
Danield

Reputation: 125443

I would use a blur event to do this rather than keyup:

$(document).ready(function() {
  $("#txtField").on("blur", function() {
    if (!$(this).val().trim())
      $(this).val(0);
  });
});

If the input is empty when it loses focus - then give it a value 0.

else - do nothing.

FIDDLE

Upvotes: 1

Alexander Abumov
Alexander Abumov

Reputation: 98

setTimeout is a bad solution. But ypu can use if-statement:

$(document).ready(function() {



 $("#txtField").keyup(function() {
var v = $(this).val();

console.log(v)
if (v == "") {
  console.log(v)
  setTimeout(function() {
    if(!$("#txtField").val()){
        $("#txtField").val(0);
    }
  }, 1000);

}


});
});

http://jsfiddle.net/guv0c5ox/

Upvotes: 0

Arg0n
Arg0n

Reputation: 8423

The problem is that you have setTimeout. If the user clears the input and then enters a value in the next second, the function in setTimeout will still go off, setting the value to 0.

Try checking the input inside the setTimeout instead, like this:

JavaScript

$("#txtField").keyup(function() {
    setTimeout(function() {
        if ($("#txtField").val().trim().length === 0) {
            $("#txtField").val(0);
        }
    }, 1000);
});

JSFiddle

Upvotes: 0

Related Questions