How to highlight text in jQuery autocomplete?

Asked

Viewed 291 times

1

I am using jQuery autocomplete and would like to underline inside the result the text being searched, I looked for some examples on the web, but only found with plug-in, like this:

Example

I tried to bring the formatted text from php with the tags html (<b>texto</b>), but the autocomplete understands literally showing the tags, it should be for security reasons and I agree :)

You can do it natively with jQuery?

Example code:

    $("#pesquisax").autocomplete({
        dataType: "json",
        minLength: 3,
        autoFocus: true,
        source: function (request, response) {
            $.ajax(
                    {
                        type: "POST",
                        url: "/solicitacao/solicitacao.localizar.nome",
                        dataType: "json",
                        data: {'term': request.term},
                        success: function (json) {
                            response(json);
                        }
                    });
        }
    }).autocomplete("widget").addClass("autocomplete");
  • 1

    Put the relevant part of the code that has sff. Mainly the part that makes the autocomplete

  • On the link you passed, have an example using jquery just change the class .autocomplete-suggestions strong {&#xA; color: #18324f;&#xA; font-weight: normal;&#xA; text-decoration: underline;&#xA;}

1 answer

1

Solution:

        open: function (event, ul) {
            $('.ui-autocomplete li').each(function () {
                var texto = $(this).html().toUpperCase();
                var busca = $("#pesquisax").val().toUpperCase();
                var troca = texto.replace(busca, "<b>" + busca + "</b>");
                $(this).html(troca);
            });
        }

Add the event open and treat each row of the list.

Complete example below:

$(document).ready(function() {
  $("#pesquisax").autocomplete({
    source: ["MARCELO", "ROBERTO", "RICARDO", "MARCIA", "MARCIO", "HELENA", "HELENI"],
    open: function(event, ui) {
      $('.ui-autocomplete li').each(function() {
        var texto = $(this).html().toUpperCase();
        var busca = $("#pesquisax").val().toUpperCase();
        var troca = texto.replace(busca, "<b>" + busca + "</b>");
        $(this).html(troca);
      });
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input type="text" id="pesquisax" value="" placeholder="Digite MAR">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.