Reputation: 229
How to count text fields that are not empty with JQuery?
Here's how I thought:
var cnt = 0;
$.each($("input[name=items]"), function(i){
if($(this).val() != ""){
cnt++;
}
});
If I use this codes, I have to write each function unconditionally. This is a waste of somehow, but is there any other way? Or is this the best way?
Upvotes: 2
Views: 3229
Reputation: 337580
There's no selector to retrieve empty input
elements, so the only way to achieve what you require is through a loop. You can use an implicit loop, though, by using filter()
instead of each()
, like this:
var cnt = $('input[name="items"]').filter(function() {
return this.value.trim() == '';
}).length;
If you don't need IE support, then this code can be shortened using an ES6 arrow function:
var cnt = $('input[name="items"]').filter((i, el) => el.value.trim() === '').length;
Upvotes: 6
Reputation: 370809
Another method that doesn't require constructing an intermediate array nor a jQuery collection is with reduce
:
const count = Array.prototype.reduce.call(
$("input[name=items]"),
(a, input) => $(input).val() === '' ? a + 1 : a,
0
);
console.log(count);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="items">
<input name="items">
<input name="items" value="foobar">
<input name="items">
You don't need jQuery for this though, since all you really need is to select the matching elements, which you can do with querySelectorAll
:
const count = Array.prototype.reduce.call(
document.querySelectorAll("input[name=items]"),
(a, input) => input.value === '' ? a + 1 : a,
0
);
console.log(count);
<input name="items">
<input name="items">
<input name="items" value="foobar">
<input name="items">
Upvotes: 0
Reputation: 3461
You can use just a CSS selector for that:
$('input[name=items][value=""], input[name=items]:not([value=""])').length
I have combined two selectors together cause if the element doesn't contain the value
attribute at all you will get the result 0 and for such cases need input[name=items]:not([value=""])
Upvotes: 0
Reputation: 177
Length can be get by a query selector
$('input[name="items"][value=""]').length
Upvotes: 0