Reputation: 4073
Below code is used to check if input value is empty, change value to 0
. But it also makes input value which is non-zero
<input type="text" value="8" class="input-mini txt">
<input type="text" value="8" class="input-mini txt">
<input type="text" value="0" class="input-mini txt">
<input type="text" value="0" class="input-mini txt">
$("input.input-mini.txt").each(function () {
var hours = $.trim($(this).val());
if(!hours){
$("input.input-mini.txt").prop("value",0)
}
});
How to set value 0
only for those inputs which are empty/null
?
Upvotes: 0
Views: 3098
Reputation: 426
You can use jQuery.isEmptyObject(object);
to check if object is empty
e.g
$("input.input-mini.txt").each(function () {
var obj.hours = $.trim($(this).val());
if(jQuery.isEmptyObject(obj)){
$(this).val(0);
}
});
Upvotes: -1
Reputation: 1074148
Use this
within the callback, and use val
, not prop
:
$("input.input-mini.txt").each(function () {
var hours = $.trim($(this).val());
if(!hours){
$(this).val(0);
}
});
!hours
is fine, because the value you're testing will always be a string, and !"0"
is false but !""
is true.
Note: Although I've written 0
, not "0"
, in the above, the value of input type=text
fields is always a string, and so it will get coerced.
Upvotes: 2