i have an ajax backend onto a mysql table with about 25 million rows,
including three searchable indexed text columns. i want a form with three
text input fields, each with autocomplete.

1) if all fields are blank when the user starts to type into one of them
then normal autocomplete happens on that field, independent of the others.

2) but if the user focuses on an empty field after an autocomplete selection
has been made in one or both of the other fields then a list of all distinct
values in that column of the big table, constrained by the selection(s)
already made, is immediately displayed without any typing.

each of the three fields has class 'auto' and there are three blocks like
this one:

$('#field1').autocomplete('suggest.php', {
  extraParams: { 
    p: 'field1',
    field2: function() { return $('#field2').data('chosen')
        ? $('#field2').val() : ''; },
    field3: function() { return $('#field3').data('chosen')
        ? $('#field3').val() : ''; } } });

so the back end can figure what's being looked for and what the constraints
are, if any.

to make a list of suggestions display on focus for 2) i have:

var lastfocus = '';
$('.auto').setOptions({ minChars: 2
}).focus(function(){
  if ( lastfocus != $(this).attr('id')
       && $(this).val() == ''
       && ( $('#field').data('chosen')
            || $('#field2').data('chosen')
            || $('#field3').data('chosen') ) )
    $(this).data('chosen', false).setOptions(
      {minChars: 0}).trigger('click').trigger('click');
  else
    $(this).setOptions({minChars: 2});
  lastfocus = $(this).attr('id');
}).change(function(){
  $(this).data('chosen', false);
  lastfocus = $(this).attr('id');
}).result(function(){
  $(this).data('chosen', true);
});

lastfocus is a hack: the focus event on a field triggers after a selection
is made by clicking. i.e. with mouse selection focus moves to the list and
then back to the text field. lastfocus deals with that.

the 'chosen' data on each field indicates if the value in that field is one
selected from the big table.

two clicks are needed after setting minChars to 0 to display the list of
suggestions. this is a quirk of the plugin.

this is my first version of a script that seems to work in a way that
wouldn't be too surprising to an unprepared user. i haven't given it much
testing yet. comments and improvements would be welcomed.

tom


Reply via email to