Reputation: 4128
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
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
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
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);
});
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
Reputation: 11447
Use map()
:
var myArray = $("input:checkbox:checked").map(function(){
return this.getAttribute("category_uid");
}).get();
Upvotes: 22
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