This is a simple search function with highlight effect, however, it highlight the whole word instead of the matched strings.
How can I make it like doing ctrl+f in browser that highlights just part of the matched word?
$(document).ready(function(){
$('input').keyup(function(){
$("ul li").removeClass('hightlight');
var searchInput = $(this).val();
if(searchInput !== ""){
$("ul li:contains('" + searchInput + "')").addClass('hightlight');
}
});
});
My code online:
Use following javascript:
$(document).ready(function(){
$('input').keyup(function(){
var searchInput = $(this).val();
$('.hightlight').contents().unwrap();
if(searchInput !== ""){
$("ul li:contains('" + searchInput + "')").each(function(i, e) {
var text = $(this).text().replace(new RegExp(searchInput, 'gm'), '<span class="hightlight">' + searchInput + '</span>');
$(this).html(text);
})
}
});
});
Here's a working demo with the required HTML and css. http://jsfiddle.net/BHqTr/
$("#search").on( "keyup", function() {
$("#items li span").contents().unwrap();
$("#items li").each(function(){
var search = $("#search").val();
var item = $(this);
var text = item.text();
var regex = new RegExp(search, 'g');
text = text.replace(regex, "<span class='highlight'>"+search+"</span>");
item.html(text);
});
});
EDIT:
This looks like a copy of the previous answer, can be removed if required.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.