1

I am using autocomplete functionality for my form. i have used below jquery script to implement the autocomplete function.

<script>
$( "#autocomplete" ).autocomplete({
  source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
});
</script>

The o/p which comes through above code is its fetching all the words related to the letter which we are entering in the input box. For example: If i am typing "C" then its fetching all the words which contains C. But i would like to have the words starting with C alone.

HTML Part is:

<label for="tags">Tags: </label>
  <input id="tags" />

Please any one help on this....Thanks

Test1234
  • 399
  • 1
  • 6
  • 17
  • 1
    Possible duplicate of http://stackoverflow.com/questions/3148195/jquery-ui-autocomplete-use-startswith – Pratik Sep 17 '13 at 10:02
  • possible duplicate of [jQuery UI Autocomplete widget search configuration](http://stackoverflow.com/questions/2382497/jquery-ui-autocomplete-widget-search-configuration) – Michael May 08 '15 at 19:24

2 Answers2

3

HTML Part :

 <label for="tags">Tags: </label>
 <input id="tags" />

Replace to:

<label for="autocomplete">Tags: </label>
  <input id="autocomplete" />

And Js Part

 <script>
 $( "#autocomplete" ).autocomplete({
    source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ]
 });
</script>

Replace to :

<script>
var tags = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ];
 $( "#autocomplete" ).autocomplete({
   source: function( request, response ) {
      var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
      response( $.grep( tags, function( item ){
          return matcher.test( item );
      }) );
  }
 });

It will work

DEMO

Nitish Kumar
  • 4,850
  • 3
  • 20
  • 38
1

Please give a try to below code:

<title>Autocomplete</title>
<body>
 <label for="tags">Tags: </label>
 <input id="tags">
</body>

Javascript:

var availableTags = [
 "ActionScript",
 "AppleScript",
 "Asp",
 "BASIC",
 "C",
 "C++",
 "Clojure",
 "COBOL",
 "ColdFusion",
 "Erlang",
 "Fortran",
 "Groovy",
 "Haskell",
 "Java",
 "JavaScript",
  "Lisp",
  "Perl",
  "PHP",
 "Python",
 "Ruby",
 "Scala",
 "Scheme"
];
$( "#tags" ).autocomplete({
   source: function( request, response ) {
    var matches = $.map( availableTags, function(tag) {
      if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
       return tag;
     }
    });
   response(matches);
 }
});

I have copied this script from jQuery forum.

Below is JsFiddle for same.

Pratik
  • 1,472
  • 7
  • 20
  • 36