SkyeBoniwell
SkyeBoniwell

Reputation: 7092

How do I filter out empty textboxes when checking their values in JavaScript?

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

Answers (3)

aethercowboy
aethercowboy

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

Alessandro Minoccheri
Alessandro Minoccheri

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

DEMO

Upvotes: 5

Rui
Rui

Reputation: 4886

You can do it all with selectors, i.e.:

$('.stringItems').not("[value='']").map(function(i, e) {
                    return e.value; 
               }).toArray();

Upvotes: 1

Related Questions