Search code examples
javascriptjqueryjquery-uijquery-ui-autocomplete

how to make bold matched text in autocomplete jquery


I need your help, I am using Autocomplete-Jquery. I need to bold text in dropdown list of autocomplete suggestions. How I can do ? Please help me in this regard. thanks.

this is my code:

   $(function () {
        $("#age").autocomplete({
            source: '{% url 'autocomplete' %}',
            appendTo: "#appendToHere",
            select: function(event, ui) {
                selectedItem = ui.item.value;
                document.getElementById("age").value = selectedItem;

                $("#searchBtn").click();
            },
        });
    });

Solution

  • Consider the following example.

    $(function() {
      var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
      ];
    
      function boldStr(needle, haystack) {
        var regex = new RegExp(needle, 'i');
        return haystack.replace(regex, "<span class='bold'>" + needle + "</span>");
      }
    
      $("#tags").autocomplete({
        source: availableTags
      }).autocomplete("instance")._renderItem = function(ul, item) {
        return $("<li>")
          .append("<div>" + boldStr($("#tags").val(), item.label) + "</div>")
          .appendTo(ul);
      };;
    });
    .bold {
      font-weight: bold;
    }
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    
    <div class="ui-widget">
      <label for="tags">Tags: </label>
      <input id="tags">
    </div>

    You can use Replace to replace a portion of a String. See More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

    You can use the Extension Points to modify the items in the list. See More: https://api.jqueryui.com/autocomplete/#method-_renderItem