I'm using jQuery UI Autocomplete plug-in. Is there a way I can use a ‘search’ button to activate the query instead of having the Autocomplete text box do it? My users have a real bad internet connection and the Autocomplete becomes hard for them to use.
Yes, it can be done. To stop the search from occurring naturally, the minimum length for a search term is increased to (an arbitrary) 1000 characters. At the same time, the search itself has been programatically triggered in a .click() event bound to a button - this is documented in the Events tab on this page. The minLength is set to 0 (so the search will actually fire) just before triggering the search and it is set back to 1000 when the autocomplete closes.
HTML:
<label for="tags">Tags: </label>
<input id="tags" />
<input type="button" value="Search"/>
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: availableTags,
minLength: 1000,
close: function(event, ui) {
$('#tags').autocomplete('option', 'minLength', 1000);
}
});
$('input[type="button"]').click(function() {
$('#tags').autocomplete('option', 'minLength', 0);
$('#tags').autocomplete('search', $('#tags').val());
});
The idea is to turn-off the autocomplete happening on text adding events. On focus we disable autocomplete and enable it upon hitting a button or pressing the enter key.
<script type="text/javascript">
$(window).load(function ()
{
// Creates the autocomplete field
$("#lookUpField").autocomplete(
{
source: ["Luis", "Erick", "Jorge", "Ana", "Anabel"],
disabled: true
});
//disables the search trigger when field selected
$("#lookUpField").focus(function ()
{
$("#lookUpField").autocomplete("disable");
});
// disables the field on keypress unless the 'enter' key
// is pressed in which case it triggers a 'search'
$('#lookUpField').keypress(function (e)
{
if (e.which == 13)
{
lookUpData();
}
else
{
$("#lookUpField").autocomplete("disable");
}
});
});
function lookUpData()
{
$("#lookUpField").autocomplete("enable");
$("#lookUpField").autocomplete("search");
}
</script>
<div>
<input id="lookUpField" type="text" />
<input type="button" value="Go" onclick="lookUpData()" />
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With