I would like to check if any div contains all words entered in an input field. However, currently I am stuck in a situation that as soon as a space is entered, it starts all over, and thus sort of acts like an OR operator instead of an AND operator. Could anyone please push me in the right direction? Thanks a lot!
This is what I have so far:
<div class="search">aa ab ac ad</div>
<div class="search">ab ba bb bc</div>
<div class="search">bb cc dd ee</div>
<script>
function search(query) {
var divs= document.getElementsByTagName('div');
var words = query.toLowerCase().split(" ");
for (var h = 0, len = divs.length; h < len; ++h) {
for (var i = 0; i < words.length; i++) {
if (divs[h].innerHTML.indexOf(words[i]) == -1) {
divs[h].style.backgroundColor = '#fff';
}
else {
divs[h].style.backgroundColor = '#ddd';
}
}
}
}
</script>
<input type="text" onkeyup="search(this.value);">
Apparently I was not very clear. My apologies.
What direction do I need to go to make it in Javascript so that it looks for if a div contains AND words[0] AND words[1] AND words[2], etc (so, in any random order)?
Right now when a split takes place, the function starts all over.
Need to also check the length of each query word:
<div class="search">aa ab ac ad</div>
<div class="search">ab ba bb bc</div>
<div class="search">bb cc dd ee</div>
<script>
function search(query) {
var divs= document.getElementsByTagName('div');
var words = query.toLowerCase().split(" ");
for (var h = 0, len = divs.length; h < len; ++h) {
for (var i = 0; i < words.length; i++) {
if (words[i].length > 0 && divs[h].innerHTML.indexOf(words[i]) >= 0) {
divs[h].style.backgroundColor = '#ddd';
break;
}
else {
divs[h].style.backgroundColor = '#fff';
}
}
}
}
</script>
<input type="text" onkeyup="search(this.value);">
Try my code :
HMTL :
<div class="search">
<div>aa cC abcc ac ad</div>
<div>ab ba bb bcc</div>
<div>bb cc dd ee cc</div>
</div>
<span>Search: </span><input type="text">
CSS :
div{
border:solid 1px #1e2a29;
margin-bottom:10px;
padding:5px;
width:auto;
}
.matched{
background-color:#f8dda9;
border:1px solid #edd19b;
margin:-1px;
border-radius:2px;
}
input[type="text"]{
margin-left:10px;
}
Javascript :
$(document).ready(function(){
$('.search > div ').each(function(i, el){
$(this).data('originalText', $(this).html());
});
$('input').keyup(function(e){
var _val = $(this).val();
var _span = '<span class="matched" >$1</span>';
$('.search div ').each(function(i, el){
var _originalVal = $(el).data('originalText');
var re = new RegExp('('+_val+')', "ig");
if(_val.length > 1 && re.test(_originalVal) >=0 ){
$(el).html(_originalVal.replace(re, _span));
}else{
$(el).html(_originalVal);
}
});
});
})
See DEMO