Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
like image 902
bluszcz Avatar asked Apr 05 '11 10:04

bluszcz


4 Answers

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.

like image 39
T.J. Crowder Avatar answered Oct 11 '22 03:10

T.J. Crowder


Use map():

var myArray = $("input:checkbox:checked").map(function(){
  return this.getAttribute("category_uid");
}).get();
like image 175
bpierre Avatar answered Oct 11 '22 03:10

bpierre


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

like image 26
Mathias Bynens Avatar answered Oct 11 '22 03:10

Mathias Bynens


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

Live Demo

like image 29
kapa Avatar answered Oct 11 '22 03:10

kapa