I currently have this code to filter out text div’s upon search.
I’ve added 4 items named "Hot Dog" with completely different SKU’s, when searched it only displays 2 items. How do I get all of the items to display?
The JS script works as it filters out the divs upon search but I can’t seem to figure out why it only displays 2 items:
$(document).ready(function() {
var $btns = $('.btn').click(function() {
if (this.id == 'all') {
$('#parent > div').fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > div').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})
var $search = $("#search").on('input', function() {
$btns.removeClass('active');
var matcher = new RegExp($(this).val(), 'gi');
$('.box').show().not(function() {
return matcher.test($(this).find('.name, .sku').text())
}).hide();
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input type="text" id="search" class="form-control" placeholder="Search product by name or sku">
</div>
</div>
<hr>
<div class="row" id="parent">
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Pepsi </p>
<p class="sku">D-1251</p>
<p>$ 2,410</p>
</center>
</div>
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Cocacola </p>
<p class="sku">D-1314</p>
<p>$ 2,410</p>
</center>
</div>
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Mountien Dwe </p>
<p class="sku">D-458</p>
<p>$ 2,410</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Burger </p>
<p class="sku">F-125</p>
<p>$ 2,410</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog </p>
<p class="sku">F-7412</p>
<p>$ 2,410</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog 2</p>
<p class="sku">F-74122</p>
<p>$ 2,4103</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog 2233</p>
<p class="sku">F-74112</p>
<p>$ 2,4103</p>
</center>
</div>
</div>
2
Answers
To correct the issue you need to define the
RegExp
object within each iteration of the loop:If you are looking to get away from using regex you can do a quick search using
includes
. Also, you have a small typo onDwe
in Mountain Dew.