Reputation: 7092
I have a web page that can contain a list of items like this:
<input type="text" class="stringItems" value="This is my string 1" />
<input type="text" class="stringItems" value="This is my string 2" />
<input type="text" class="stringItems" value="This is my string 3" />
<input type="text" class="stringItems" value="This is my string 4" />
<input type="text" class="stringItems" value="This is my string 5" />
<input type="text" class="stringItems" value="This is my string 6" />
Before sending the data off to my server, I put them all in an array like this:
$('.stringItems').map(function(i, e) {
return e.value;
}).toArray());
So this all works great.
But now I need to filter out <input>
elements that may contain an empty value like this:
<input type="text" class="stringItems" value="" />
Basically, I don't want these to be part of the array UNTIL they have a value.
Is there a jquery method that I can use to filter out elements with empty values?
Upvotes: 2
Views: 126
Reputation: 444
You're probably wanting to use the filter() method: http://api.jquery.com/filter/
e.g.
$('.stringItems').filter(function(i, e) {
return e.value != '';
}).map(function(i, e) {
return e.value;
});
Upvotes: 1
Reputation: 35973
try this:
$('.stringItems').map(function(i, e) {
if(e.value.trim() != '')
return e.value;
}).toArray();
See in the demo the console.log inside your console please and you can see your array without empty value
Upvotes: 5
Reputation: 4886
You can do it all with selectors, i.e.:
$('.stringItems').not("[value='']").map(function(i, e) {
return e.value;
}).toArray();
Upvotes: 1