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: /
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/2shadgtw/2/
Share Improve this question edited Dec 7, 2015 at 9:36 Praveen Kumar Purushothaman 167k27 gold badges213 silver badges260 bronze badges asked Dec 7, 2015 at 9:29 SoraSora 2,55119 gold badges77 silver badges151 bronze badges5 Answers
Reset to default 3Don'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/5hm6e8hL/
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
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
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/guv0c5ox/
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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745208771a4616719.html
评论列表(0条)