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) ?
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');
});
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') );
});
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