I am trying to make a simple jQuery word search based on an input of type text and highlighting text. How can I do this for multiple words? This code is only working for a single character.
Html
<input type="text"/>
<div>John Resig
George Martin
Malcom John Sinclair
J. Ohn
Sample text
</div>
CSS
span {
background : red
}
JS
$("input").keyup(function() {
var mysearchword = $("input:text").val();
var word = mysearchword;
$( "div:contains('"+word+"')" ).html(function(i,html) {
var re = new RegExp(word,"g");
return html.replace(re,'<span>'+word+'</span>')
});
});
JsFiddle
If you have a predefined set of elements to target then
var $para = $('.para')
$("input").keyup(function() {
$para.find('span.highlight').contents().unwrap();
var mysearchword = this.value.trim();
if (mysearchword) {
var re = new RegExp('(' + mysearchword.trim().split(/\s+/).join('|') + ')', "gi");
$para.html(function(i, html) {
return html.replace(re, '<span class="highlight">$1</span>')
});
}
});
span.highlight {
background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" />
<div class="para">John Resig George Martin Malcom John Sinclair J. Ohn Sample text</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With