bluszcz
bluszcz

Reputation: 4128

Getting array of values from jQuery object

I have following object:

$("input:checkbox:checked")
[
<input class=​"li_checker" type=​"checkbox" category_uid=​"1.3" category_language=​"da">​, 
<input class=​"li_checker" type=​"checkbox" category_uid=​"1.3.1" category_language=​"da">​
]

If there is any helper in jQuery which allows me to get value of "category_uid" for all elements and returns it as the another array? Expected result:

["1.3", "1.3.1"]

Upvotes: 10

Views: 16654

Answers (6)

gion_13
gion_13

Reputation: 41533

Here's a more "pluginy" way to do this:

(function($){

    $.fn.getAttributes = function(attribute){
        var result = [];
        $(this).each(function(){
             var a = $(this).attr(attribute);
             if(a)
                 result.push(a);
        });
        return result;
    }
})(jQuery);

and then use it as follows :

var result = $("input:checkbox:checked").getAttributes("category_uid");

Haven't tested it, but it should work just fine.

Upvotes: 0

Mathias Bynens
Mathias Bynens

Reputation: 149534

As bpierre suggested, use .map(). His answer is correct.

If you need this behavior for different attributes, you might as well write is as a reusable function (“jQuery plugin”):

jQuery.fn.pluck = function(attr) {
  return this.map(function() {
    return this.getAttribute(attr);
  }).get();
};

$('input:checkbox:checked').pluck('category_uid'); // ["1.3", "1.3.1"]

P.S. category_uid is not a valid attribute in HTML. Consider using custom data-* attributes instead, e.g. data-category-uid="foo".

Upvotes: 7

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Just for the fun of it, a third way, this one using attr:

var categories = [];
$("input:checkbox:checked").attr("category_uid", function(index, value) {
    categories.push(value);
});

Live example


Off-topic: If you want to have arbitrary, custom attributes on HTML elements, recommend using the data- prefix defined by HTML5 (details). You can use it now, even if you're not using the HTML5 doctype (this is one of the places where HTML5 is just codifying — and reining in — current practice), and it future-proofs a bit.

Upvotes: 5

bpierre
bpierre

Reputation: 11447

Use map():

var myArray = $("input:checkbox:checked").map(function(){
  return this.getAttribute("category_uid");
}).get();

Upvotes: 22

russellfeeed
russellfeeed

Reputation: 627

Something like

var checked_cats = new Array();
$("input:checkbox:checked").each(function() {
   checked_cats.push($(this).attr('category_uid'));
});

(not tested)

p.s. saw your tweet.

Upvotes: 1

kapa
kapa

Reputation: 78671

var myarray=[];
$("input:checkbox:checked").each(function () {
  myarray.push($(this).attr('category_uid'));
});

Live Demo

Upvotes: 1

Related Questions