I have this great function that works like a charm. The script highlights the words in the content as long as it matches. However, I can seem to find the right code to display an error if no result matches the query.
This is the HTML:
<div id="search">
<input type="text" id="searchtxt" />
<input type="button" value="Find" onClick="replaceText();" id="search-resultButton" />
</div>
<p>Copy goes here</p>
And this is the function:
function replaceText() {
$("body").find(".search-result").removeClass("search-result");
var searchword = $("#searchtxt").val();
var filter = new RegExp("\\b"+searchword+"\\b", "ig");
if(searchword!=""){
$("body").each(function( ) {
$(this).html($(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>")) ;
});
}
}
I guess I'm looking for something like:
if(searchword!=""){
$("body").each(function( ) {
$(this).html($(this).html().replace(filter,"<span class='search-result'>" + searchword + "</span>")) ;
});
} else {
alert(“There is no match”)
}
But I can't seem to find the way to write it. Any help would be appreciated.
Thank you!