zenpoy
zenpoy

Reputation: 20126

Google-like jQuery UI autocomplete

Is it possible to send the server only the last 3 words in the textarea and to autofill the best result, letting the user keep typing in (similar to Google auto complete)?

I want the behavior to be:

  1. N[ew]
  2. New[er]
  3. New(SPACE)[er]
  4. New [York]
  5. New c[ar]
  6. New cat [food]
  7. New cat (TAB) [food]
  8. New cat food [makes]
  9. ...
  10. New cat food is good for your cat's [health]

(clarification: the [square brackets] indicates the suggestion that is automatically being typed in, the bold text indicates the part being sent to the server, (TAB) and (SPACE) indicates tab and space key presses)

I already a have function on the server for predicting the next word (using Markov chains) and I have integrated jQuery UI autocomplete, but currently it just sends all the text to the server and creates a list with all the suggestions to choose from, once you choose it changes the whole text.

So it eventually comes to these issues:

  1. How to send only the last part?
  2. How to append + select the suggested word?
  3. How to select on Tab key?

Upvotes: 0

Views: 823

Answers (1)

zenpoy
zenpoy

Reputation: 20126

Okay - here is the solution (and here is the result):

1 + 2: Instead of managing a single input box, I use two identical size textarea's, the first (#text-area) is enables and with transparent background and the other (#suggestions) is disabled and with gray text color. I use the source callback to do all the work:

$('#text-area').autocomplete({ ...

source: function( request, response ) {
        if (request.term.length < 3) {
          return false;
        }
        $.getJSON( $SCRIPT_ROOT + '/_get_word', {
          term: request.term
        }, function(data) {
            $('#suggestions').val(data.result) //suggestion is the disabled textarea
          }
          );
        return false;
      }, 
 ...
    });
});

3: the tab key selection is done with triggering the autocomplete search event:

$('#text-area').live( "keydown",'textarea', function( event ) {
        if ( event.keyCode === $.ui.keyCode.TAB) {
          event.preventDefault();
          $('#text-area').val($('#suggestions').val());
          $("#text-area").autocomplete('search', $('#text-area').val());
      }
});

Upvotes: 2

Related Questions