John Davidson

javascript - Highlighting search keyword

0 comments
Message:


I created a simple database and there is a live search,i want to know how to highlighting search keywords in the table. I've been using other means but still it doesn't work. please help me


this is my code :


$(document).ready(function(){
load_data();

function load_data(search){
$.ajax({
url:"get_data.php",
method:"POST",
data: {
search: search
},
success:function(data){
$('#hasil').html(data);
}
});
}
$('#search').keyup(function(){
var search = $("#search").val();
load_data(search);
});


function highlight_word(hasil)
{
var text = document.getElementById("search").value;
if(text)
{
var pattern=new RegExp("("+text+")", "gi");
var new_text=hasil.replace(pattern, "<span class='highlight'>"+text+"</span>");
document.getElementById("hasil").innerHTML=new_text;
}
}

html :


  <input type="text" class="form-control" id="search" name="search" >
<div id="hasil"></div>


My Answer:
To highlight the search keyword in the table, you can modify your `load_data` function to include the `highlight_word` function. Here's an updated version of your code:

javascript
$(document).ready(function(){
load_data();

function load_data(search){
$.ajax({
url: "get_data.php",
method: "POST",
data: {
search: search
},
success:function(data){
$('#hasil').html(highlight_word(data));
}
});
}

$('#search').keyup(function(){
var search = $("#search").val();
load_data(search);
});

function highlight_word(hasil){
var text = $("#search").val();
if(text){
var pattern = new RegExp("(" + text + ")", "gi");
var new_text = hasil.replace(pattern, "$1");
return new_text;
}
return hasil;
}
});


In this updated code, the `highlight_word` function now returns the modified text with the search keyword highlighted. The `load_data` function now calls `highlight_word` before setting the HTML content of `#hasil`.

Make sure to add the following CSS to your stylesheet to style the highlighted text:

css
.highlight {
background-color: yellow;
}


With these changes, the search keyword should now be highlighted in the table when performing a search.

Rate this post

3 of 5 based on 6187 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us