AndreiBogdan
AndreiBogdan

Reputation: 11174

JQuery. Finding div which has specific data() associated to it

Using the data() function I add two values to some divs ($oRow points to divs)

$oRow.data("more", {moreValue: 750, moreIndex: 4});

Later on I'm trying to find the div (there is only one) which has a specific value for moreIndex

I'm doing it like so:

$oMore = $(".meter_battery_row").filter(function(){
                   return $.data(this, "more").moreIndex == 4;
                   }); 

But it doesn't seem to work. After the above line I display window.alert($oMore) but it seems it doesn't get to this line, so it runs in some kind of problem in the filter function.

Anyone got any ideas?

EDIT

.meter_battery_row are the classes of divs to which i attach the data values. ($oRow is of class .meter_battery_row)

Upvotes: 0

Views: 66

Answers (4)

bingjie2680
bingjie2680

Reputation: 7773

The problem is that when you call $.data(this, "more") only one of elements will return the object {moreValue: 750, moreIndex: 4}, the rest will return undefined. then when you call undefined.moreIndex you will get an error. try to do this:

 return $.data(this, "more") && $.data(this, "more").moreIndex == 4;

Upvotes: 1

Dr.Molle
Dr.Molle

Reputation: 117354

First check $.data(this, "more")

return  ($.data(this, "more") && $.data(this, "more").moreIndex == 4);

Otherwise you will receive an error when not all elements have more-data, and the filtering stops.

Upvotes: 1

Calvein
Calvein

Reputation: 2121

You can add it data- attribute so you can retrieve it easier after and still use $.fn.data() :

$oRow.attr('data-moreIndex', 4).attr('data-moreValue', 750);
// ...
$oMore = $('.meter_battery_row[data-moreIndex="4"]');

Here is a live example.

Upvotes: 1

mas-designs
mas-designs

Reputation: 7546

$('div.meter_battery_row[data-moreIndex="4"]') does not help you ? 

normally the .data() function add's the custom value to your div as a data-... prefixed attribute.

You could use attribute selectors to get your specified div.

Inspect the element you are trying to select with firebug and you will see that your moreIndex is saved as an attribute to the div element.

Upvotes: 1

Related Questions