dylankbuckley
dylankbuckley

Reputation: 1647

Put value of buttons into array

I currently have about a dozen html buttons on a page, all with a unique value attribute assigned to them.

Firstly, I want to be able to get the values of these buttons and assign them into an array. Here is my code:

            var myArray = [];

            $("#buttonID").each(function(){
                myArray.push($(this).attr("value"));
            });

This works, however only takes the value from the first button, and then ignores the rest, despite them all have the same ID. Have I done something wrong with my .each() ?

Once I have solved that, I would like to then modify the above to only add values of those buttons with ".active" classes on them. i.e a user has selected them.

Upvotes: 0

Views: 1265

Answers (2)

PeterKA
PeterKA

Reputation: 24638

Let's say you decided to use a common class for your buttons instead of an ID. Example:

<button class="my-class".......

There's a wonderful jQuery method that would put the values of all the button's with this class in an array like so:

var myArray = $('.my-class').map(function() {
    return this.value;
})
.get();

Upvotes: 0

Mi-Creativity
Mi-Creativity

Reputation: 9654

Your selector represents an ID hence the #this why it picks only one because ID's are supposed to be unique, you need to pick them by class name like .className after assigning this class name to all of your buttons

have a loonk at this http://www.w3schools.com/jquery/jquery_ref_selectors.asp

Upvotes: 2

Related Questions