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"]
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.
Use map()
:
var myArray = $("input:checkbox:checked").map(function(){
return this.getAttribute("category_uid");
}).get();
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"
.
var myarray=[];
$("input:checkbox:checked").each(function () {
myarray.push($(this).attr('category_uid'));
});
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With