Reputation: 4009
I'm putting together a search function that searches through multiple data attributes on a lot of divs on a page. Below is the code I have working for this. My problem I've come across is that it only seems to search the first word each data attribute except the last one.
var filter = $(this).val();
var regExPattern = "gi";
var regEx = new RegExp(filter, regExPattern);
$(".box").each(function(){
if (
$(this).data('attr1').search(regEx) &&
$(this).data('attr2').search(regEx) &&
$(this).data('attr3').search(regEx) &&
$(this).data('attr4').search(regEx) < 0
)
{
//Do Something
}
else
{
//Do Something else
}
});
I've put together a fiddle that replicates this problem here.
I've tried different combinations of searching... such as putting all the data attributes into an array and then searching elements one by one, but that takes along time to complete.
I would be much appreciated if anyone can help with this?
Upvotes: 0
Views: 172
Reputation: 664599
Your condition is confusing. .search()
returns the index of a match or -1
. So it yields a falsy value (0
) only when the regex is found at the start of the string, and a truthy number otherwise. So change it to
$(this).data('attr1').search(regEx) < 0 &&
$(this).data('attr2').search(regEx) < 0 &&
$(this).data('attr3').search(regEx) < 0 &&
$(this).data('attr4').search(regEx) < 0
Or, since you don't need the position, switch to regEx.test()
Upvotes: 1