10

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"]
3
  • Have you tried the .attr()? api.jquery.com/attr Commented Apr 5, 2011 at 10:11
  • @chchrist .attr() will only return the attribute value for the first element in the set. Commented Apr 5, 2011 at 11:00
  • you can use .each() to loop their .attr() Commented Apr 5, 2011 at 11:26

6 Answers 6

22

Use map():

var myArray = $("input:checkbox:checked").map(function(){
  return this.getAttribute("category_uid");
}).get();
Sign up to request clarification or add additional context in comments.

3 Comments

Important to note that map doesn't return an array, it returns a jQuery wrapper around an array. You have to use .get() to get the actual array.
That's a nice solution. My first through was what Russell and bazmegakapa had suggested.
I used this one since was shortest.
7

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".

Comments

5

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.

2 Comments

I've just realized that this relies on undocumented behavior (leaving the attribute alone if the function doesn't return anything or returns undefined). So I've logged a ticket to document it (or not, of course, if it's not desired behavior).
@bluszcz: No worries, have fun. (Spain, eh? And I would have though the Czech Republic, from your username...)
1
var myarray=[];
$("input:checkbox:checked").each(function () {
  myarray.push($(this).attr('category_uid'));
});

Live Demo

2 Comments

i dont think he only needs the checked ones
He suggested something like that in his question, that's why I used this selector.
1

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.

6 Comments

And how is this different from my answer posted earlier?
@bazmegakapa: He uses new Array() rather than the more reliable, and more concise, []. ;-)
older versions of ie will throw an error if you "push" something to an array declared without the "new" keyword ;)
@gion_13: I don't know what version of IE you're talking about, but [] has been correct array literal syntax for donkey's years (like, before JavaScript was handed to the ECMA; eons ago in computing terms). It works on IE6. Fortunately, I don't have (or need) access to earlier versions than that.
@gion_13: push is supported in IE since version 5.5. Even on that version, I haven't found any evidence about the bug you talked about.
|
0

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.

2 Comments

With respect: Very inefficient, you're repeating calls all over the place (to $(), to attr()). Bad enough in application code, but plugin code should strive for efficiency. (Also, you forgot to declare your $ argument, but good form [intending to] use one.)
T.J. makes very good points. Also, why reinvent the wheel (.map()) when jQuery already has such a method?

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.