CairoCoder CairoCoder - 4 months ago 24
jQuery Question

How to trigger jquery autocomplete manually on keyup

I want to trigger the jquery autocomplete manually on keyup, only after pressing the asterisk "*" by the end of the input.

Here's what I did:

<input type="text" name="test" id="mainSearchBox">

var availableTags = [
"Perl",
"PHP",
"Python",
"Ruby"
];
$('input#mainSearchBox').keyup(function(){
var value = $('input#mainSearchBox').val();
if(value.substr(value.length - 1) == "*"){
$(this).autocomplete({
source: availableTags,
minLength:0
});
} else {
$(this).autocomplete("close");
}
});


jsfiddle

Answer

Here, Try doing it like this :

var availableTags = [
  "Perl",
  "PHP",
  "Python",
  "Ruby"
];
$('input#mainSearchBox').autocomplete({
  source: availableTags,
  minLength: 0
});

$('input#mainSearchBox').autocomplete("disable");

$('input#mainSearchBox').keyup(function() {
  var value = $('input#mainSearchBox').val();
  var last = value.substr(value.length - 1);
  if (last == "*") {
    var valToSearch = value.substr(0, value.length - 1);
    $('input#mainSearchBox').autocomplete("enable");
    $('input#mainSearchBox').autocomplete("search", valToSearch);
  } else {
    $('input#mainSearchBox').autocomplete("disable");
  }
});
<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" name="test" id="mainSearchBox">

Have a look at :

  1. http://api.jqueryui.com/autocomplete/#method-search
  2. http://api.jqueryui.com/autocomplete/#method-enable
  3. http://api.jqueryui.com/autocomplete/#method-disable

What I have done :

  1. Loaded/Initialized autocomplete on the textbox and then disabled it.
  2. Whenever key-up event is triggered, I checked if last character in the input is *,

a. if it is, then enable autocomplete and force search on the text-box, with the input value without *. b. If it is not, then disable the autocomplete.