2

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?

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

4 Comments

Should probably trim the value just to be sure.
Thanks for the suggestion I have edited now, it's a good practice in this control to use trim! thanks again @Karl-AndréGagnon
@Alessandro Minoccheri You don't have to check != '' cause '' is a false itself. So e.value.trim() is enough. jsfiddle.net/TL8nC/2
@Bright you are right, but it is better, in this case, to use !==. @Alessandro, I know, i am anoying, but it is better to use $.trim(string) than string.trim() for browser support (ie9 doesnt supprot string.trim()).
1

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

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

Comments

1

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;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.