0

I am trying to get back an array selecting the class value but I only get the last value.

So this:

<input class="test" value="Example 1" />
<input class="test" value="Example 2" />
console.log($(".test").val());

Returns me this

Example 1

How can I get all values of the class? I want to save it in a variable so I can send it with AJAX.

0

7 Answers 7

3

You can do this using .map() method like:

var data = $(".test").map(function () {
    return this.value;
}).get();   // ["Example 1", "Example 2"]
Sign up to request clarification or add additional context in comments.

Comments

1

this is because there are many elements that satisfy the selector ".test", so $(".test") returns an array with all instances that have the class "test", so you should probably loop through the array it returns, like this;

$(".test").each(function(){
   console.log($(this).val());
});

Comments

1
var values = [];
$(".test").each(function(){
   values.push($(this).val());
});
console.log(values);

2 Comments

didn't see your answer when i wrote mine... relax. + you didn't fully answer his question, he wanted an array of the values.
no problem. . .but I don't see the word array anywhere in his question
0

Be aware that $('.test') already returns an array with all elements in the DOM that have the class test.

So if you need all their values, just iterate over the returned array storing the values into a new array.

Comments

0

The function $(".test") already returns an array; the array of elements that have class "test". So one option would be to map that array to an array of values. E.g.

var valueArray = $.map($(".test"), function(input, indx) {
    return input.value;
});
for (var i = 0, v; v = valueArray[i]; ++i) {
    console.log(v);
}

You could also iterate with each() and create your own array

1 Comment

Ah, I'm too slow typing :) others already suggested the same :)
0

Try this code:

var myArray = $('.test').map(function(){
   return $(this).val();
}).get();

You will get the variable myArray as an array of input values, check this out here:

http://jsfiddle.net/CG8kj/

Comments

0

Try this

var x = $(".test");

this will return the array of elements and then you can process the array to get all values.

  var x = $(".test");
            for (var i = 0; i < x.length; i++) {
                alert(x[i].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.