1

I have the following form:

                <input type="text" name="name1" id="names1" class="names" value="" placeholder="1) Name Here . . .">
                <input type="text" name="name2" id="names2" class="names" value="" placeholder="2) Name Here . . .">
                <input type="text" name="name3" id="names3" class="names" value="" placeholder="3) Name Here . . .">
                <input type="text" name="name4" id="names4" class="names" value="" placeholder="4) Name Here . . .">

I am trying to create an array when the user clicks the submit button that stores each name:

var values = $('.names').map(function() { return this.value; }).get();

It works, but it also collects the empty fields which I do not need. I figure I require a conditional For statement for this, but I can't manage the syntax for it.

Thanks

2 Answers 2

2

Try this:

var values = $('.names').map(function() { if(this.value.trim() != '') return this.value; }).get();

Or:

var result = [];
var elements = getElementsByClassName('names');
for(var i = 0; i < elements.length; i++){
    if(elements[i].value.trim() != '')
          result.push(elements[i].value);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Jesus. That was record response time. +5
0

just select all .names with non empty value

var values = $('.names[value!=""]').map(function() { return this.value; }).get();

in real world you will need to store names also:

var values = $('.names[value!=""]').map(function() { 
    return {name: this.name,value: this.value};
}).get();

http://jsfiddle.net/oceog/7ZcbY/

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.