views:

28

answers:

1

I'm trying to highlight the text that matches the query in a live search using jquery.highlight. The live search works fine but the styling for the highlighting applies then it disappears. Am I doing something wrong?

JQuery

$(document).ready(function() {
    $("#search").bind("keyup", function() {
    var form = $(this).parents("form");
    var query = $(this).val();
    var formData = form.serialize();

    $.post("/questions/new/search", formData, function(html) { 
      $("#questionList").html(html);
    });

    $(".question").highlight(query);
  });
});

HTML

<form action="/questions" method="get">
    <input id="search" name="search" type="text" />
</form>

<div id="questionList">
    <div class="question">What is the 1 + 1?</div>
    <div class="answers">2</div>
</div>
+2  A: 

Yes, you should execute $(".question").highlight(query) in the http request response handler right after $("#questionList").html(html) this way:

$(document).ready(function() {
    $("#search").bind("keyup", function() {
    var form = $(this).parents("form");
    var query = $(this).val();
    var formData = form.serialize();

    $.post("/questions/new/search", formData, function(html) { 
      $("#questionList").html(html);
      $(".question").highlight(query);
    });

  });
});
Andrea Zilio
Thanks, that did the trick.
Soliah