Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the rel attribute using Jquery .each

I have a list of checkboxes with different rel values. My following jquery code is giving my undefined.

var checked_keys=[];
$("input[type='checkbox']:checked").each(function(index, value){
    checked_keys.push( value.attr('rel') );
});

However, If I use "this", it works.

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

Can someone explain what is the difference between .each with value and .each with $(this) ?

like image 528
Gundam Meister Avatar asked Sep 26 '22 07:09

Gundam Meister


2 Answers

In jQuery, the $.each method has a callback that return the index and the DOM node, and the latter is the native DOM node, not wrapped in jQuery, so it needs to be wrapped to work with jQuery methods like attr(), otherwise you'd have to use native methods like getAttribute('rel')

var checked_keys=[];
$("input[type='checkbox']:checked").each(function(index, value){
    checked_keys.push( $(value).attr('rel') );
});

As a sidenote, there's also a $.map method, that seems more appropriate

var checked_keys = $("input[type='checkbox']:checked").map(function(index, value){
    return $(value).attr('rel');
});
like image 188
adeneo Avatar answered Oct 29 '22 02:10

adeneo


If you log a jQuery object, you can see that all the selected elements are listed out numerically in an Array-style fashion.

var domElement = jqueryObject[0];//returns the first element of the jquerycollection

When you use the .each function, it will pass the native domElement as the value parameter, and not a jQuery object of that element. This means you have to wrap the domElement with jquery like this.

$(domElement).attr('rel');

This makes your code look like this.

var checked_keys=[];
$("input[type='checkbox']:checked").each(function(index, vale){
    checked_keys.push( $(value).attr('rel') );
});
like image 20
Swimburger Avatar answered Oct 29 '22 03:10

Swimburger