Reputation: 1226
I am working on a simple method for filtering elements depending on their class. The user checks a checkbox and the jQuery does it's thing fine and turns off any element depending on the class. The line that turns off the element, and how the elements look is:
$('#ItemList div:not(.' + Filter + ')').hide();
<div class="1 2 3">asdf</div>
However I want to be able to use the data-xxxx attribute to do this instead of the class attribute, but I am having problems actually selecting the elements this way. What I have is below:
$("#ItemList div:not([data-filter'" + Filter + "'])").hide();
<div data-filter="1 2 3">asdf</div>
So, how do I go about selecting the element using the data-filter attribute instead of the class? The methods I have found on here are not working for me! Many thanks.
UPDATE
Okay, so James Allardice's reply did the trick. But has caused another issue that I probably should I said in the original post.
Each data-xxxx attribute can have a number of values, I need this filter to work so that if any one of the value shows up it will not hide the element.
$('#Filters input').change(function()
{
$('#ItemList div').show();
$('input').each(function()
{
var Checked;
if(Checked = $(this).attr('checked'))
{
var Filter = $(this).attr('data-filter');
$("#ItemList div:not([data-filter='" + Filter + "'])").hide();
};
});
<div data-filter="1">1</div>
<div data-filter="1 3">1 3</div>
So for example if a checkbox with the following attribute is checked it will show both divs:
data-filter="1"
But if the attribute is like this it will only show the second:
data-filter="3"
Upvotes: 1
Views: 8368
Reputation: 2527
You can use the jQuery filter function like this:
$("#ItemList div").filter(function()
{
var attr = $(this).attr('data-filter');
var filterArr = attr.split(" ");
return $.inArray(Filter, valArr) == -1;
}
).hide();
I haven't tested this but it should work. You can find the inArray documentation from the this link and the documentation for the filter function from this link
Upvotes: 2
Reputation: 10607
jQuery('[data-name=something]') or for not, jQuery('[data-name!=something]')
Check out the attribute selectors available here: http://api.jquery.com/category/selectors/
Upvotes: 0
Reputation: 165951
You were close. You're just missing the =
character:
$("#ItemList div:not([data-filter='" + Filter + "'])").hide();
// ^ You missed this
Here's a working example.
Upvotes: 4