Aayush Karki
Aayush Karki

Reputation: 841

Form autocompletion in jquery

The following is a slighty modified code that i found on Tutorial's Point. I want to make an autocomplete form field where if a user types a phone number, the name of the person to which the number belongs to appears. How do i do it? I intend to pass a tuple like : [("55555", "John Doe"), ("6666", "Jane Doe")...] to var phonenumbers

<!doctype html>
    <html lang = "en">
       <head>
          <meta charset = "utf-8">
          <title>jQuery UI Autocomplete functionality</title>
          <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
             rel = "stylesheet">
          <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
          <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>



   <!-- Javascript -->
      <script>
         $(function() {
            var phonenumbers = [
                "555111000"

            ];
            $( "#automplete-2" ).autocomplete({
               source: phonenumbers,
               autoFocus:true
            });
         });
      </script>
   </head>

   <body>
      <!-- HTML --> 
      <div class = "ui-widget">

         <label for = "automplete-2">Tags: </label>
         <input id = "automplete-2">
      </div>
   </body>
</html>

Upvotes: 0

Views: 29

Answers (1)

jacman
jacman

Reputation: 191

Did you checked the documentation ?

http://api.jqueryui.com/autocomplete/#method-_renderItem

This should help you :)

var phonenumbers = [
  {"label":"555111000", "name":"John"},
  {"label":"555111001", "name":"Jane"}
];

$( "#myinput" ).autocomplete({
  minLength: 0,
  source: phonenumbers
})
//
// This is the important part
//
.autocomplete( "instance" )._renderItem = function( ul, item ) {
  return $( "<li>" )
    .append( "<div>" + item.name + " : " + item.label + "</div>" )
    .appendTo( ul );
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="myinput" />

Upvotes: 2

Related Questions