Tags: How to Search any text in whole web page using Jquery
Hello Readers, today we will learn that how to
search any content in web page and highlight that.
To achieve this, we will use J Query
mark.js script file. You can download it from here or any trusted source you know.
Editor : You can use any editor to try this
example like notepad, notepad++, bracket or Visual Studio. I suggest to use
Visual Studio because it has great feature of Intellisense which helps you to get suggestions and type quick.
Steps –
Create a New Website in Visual
Studio. File menu > New > Web Site
Right click on Project in Solution Explorer
> Add > Add New Item Option
Now right click on Project from Solution
Explorer > Add > Existing Item… option
<!DOCTYPE html>
<html>
<head>
<title>Highlight Search</title>
<meta charset="utf-8" />
<script src="jquery.min.js"></script>
<script src="jquery.mark.min.js"></script>
<script>
$(document).ready(function (){
var mark = function () {
// Read the keyword
var keyword = $("input[name='keyword']").val();
// Determine selected options
var options = {};
$("input[name='opt[]']").each(function () {
options[$(this).val()] = $(this).is(":checked");
});
// Remove previous marked elements and mark
// the new keyword inside the context
$(".context").unmark({
done: function () {
$(".context").mark(keyword, options);
}
});
};
$("input[name='keyword']").on("input", mark);
$("input[type='checkbox']").on("change", mark);
});
</script>
</head>
<body>
<div>
<span>
<input id="btnQuickSearch" type="button" value="QUICK SEARCH" />
</span>
<input type="text" name="keyword" style="width:300px;" placeholder="Enter Keyword
Here...">
<span>Search Options:</span>
<input type="checkbox" name="opt[]" value="separateWordSearch" checked> Separate Word Search
<input type="checkbox" name="opt[]" value="diacritics" checked> Diacritics
</div>
<br />
<br />
<div id="divQuickSearch" class="context">
This is the text for the searching
Test.
</div>
</body>
</html>
About
above code: You should be careful about the name and class attribute
of controls. Because in script code, the action is performed with the help of
these attributes. Have look on following images:
You can apply this script for other tags
like table, span, p etc.
Happy Coding
I hope this will help. Send me your
feedback/suggestions/queries.
Rudra Pratap Singh
Software Engineer
Software Engineer