3

I have a list of jQuery items found using

var groupedItems = $('div[data-group-id="'+groupId+'"]');

Each grouped item has a propery called

data-info={"isAvailable":"true","isValid":"false"}

from the groupedItem I want to filterOut only which has property isAvailable=true.

How can I filter based on data attribute?

2 Answers 2

1

You can use jQuery filter() method to filter jQuery collection and where you can use data() method to get the property.

var groupedItems = $('div[data-group-id="' + groupId + '"]');

var res = groupedItems.filter(function() {
  // since property value starts with {, the data method
  // would parse if it's a valid JSON. So simply get the
  // property from the object and compare
  return $(this).data('info').isAvailable == 'true';
})
Sign up to request clarification or add additional context in comments.

3 Comments

has to be return $(this).dataObject('info').isAvailable
@hilda_sonica_vish : since value is string you need to compare
@hilda_sonica_vish : or you need to update the json with boolean instead of string data-info='{"isAvailable": true,"isValid":"false"}'
1

You can use filter to filter groupedItems which have isAvailable set to true inside info data attribute. Access data attribute using data().

var groupId = 1;
var groupedItems = $('div[data-group-id="'+groupId+'"]');
var info = groupedItems.filter(function(){ 
  return $(this).data('info').isAvailable == 'true';
});
console.log(info);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-group-id=1 data-info={"isAvailable":"true","isValid":"false"}>foo</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.