Andrea
Andrea

Reputation: 127

jQuery exclude element by data value

I have this HTML code:

<ul class="chosen-results">
    <li data-value="-">-</li>
    <li data-value="145">145</li>
    <li data-value="170">170</li>
    <li data-value="300">300</li>
</ul>
<ul class="chosen-results">
    <li data-value="-">-</li>
    <li data-value="0">No</li>
    <li data-value="1">Yes</li>
</ul>

I need to hide all element with data-value that match to an array of values. I've already tried:

var array = ['145', '0', '300'];
var $li = $('.chosen-results li').filter(function(i) {
    return $(this).data('value') != array[i];
});

but $li contain all <li> element!

Upvotes: 2

Views: 301

Answers (2)

gavgrif
gavgrif

Reputation: 15509

This works - create an array of the elements you wish to hide then iterate through it and using a regex filter, if the element matches then hide it. Note that this can work in the reverse as well - simply hide all li's at the top of the function and then swap the .hide() to .show() to display the matching elements. Only thing - I had to make the yes / no values as "00" and "01" to ensure that they are unique and didn't just match "0" and "1".

	$(function() 
	{  
	
		var list=["145","300","00"];
		
		$('.chosen-results li').each(function(){
		for (i=0;i<list.length;i++)
			{
				var rex = new RegExp(list[i], 'i');
				$('.chosen-results li').filter(function() {
						return rex.test($(this).attr('data-value'));
							}).hide();
			}
		})
	})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css" /> 
    <title>List Filter</title>
</head>
<body>

<ul class="chosen-results">
    <li data-value="-">-</li>
    <li data-value="145">145</li>
    <li data-value="170">170</li>
    <li data-value="300">300</li>
</ul>
<ul class="chosen-results">
    <li data-value="-">-</li>
    <li data-value="00">No</li>
    <li data-value="01">Yes</li>
</ul>
</body>
</html>

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use Array.prototype.indexOf() at this context,

var array = ['145', '0', '300'];
var $li = $('.chosen-results li').filter(function(i) {
console.log( typeof $(this).data('value'));
    return array.indexOf($(this).data('value') + "") > -1;
}).hide();

DEMO

Upvotes: 1

Related Questions