Reputation: 644
I got certain string, and I want to highlight the substring typed in the text input.
Here is a fiddle: http://jsfiddle.net/rFGWZ/17/
It is working fine only , when I type the initial string, but when I type fe. 15
in the input, it doesn't highlight the 15
but 21
instead... it is always highlighting the numbers at the beggining, so could someone help me modify it, so it will highlight the string I type in the text input?
Upvotes: 0
Views: 1674
Reputation: 382130
You can use this :
firstCell.html(id.replace(value, '<span class=highlight>'+value+'</span>'));
instead of
firstCell.html($("<span />").addClass("highlight").text(id.slice(0, value.length)));
firstCell.append(id.slice(value.length, id.length));
Demo : http://jsfiddle.net/qgBt8/
EDIT : case insensitive version
Upvotes: 2
Reputation: 3960
I would use a regular expression to solve this. This also takes into account case of characters.
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var firstCell = $row.children("td:first");
var id = $row.children("td:first").text();
if (id.indexOf(value) === -1) {
$row.children("td:first").text(id);
$row.hide();
}
else {
var re = new RegExp(value, "g"); //global replace
firstCell.html(id.replace(re, "<span class=\"highlight\">" + value + "</span>"));//replace all instances of the characters
$row.show();
}
}
});
});
Upvotes: 0