Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use rails3-jquery-autocomplete plugin for multiple words autocomplete

I have use rails3-jquery-autocomplete plugin and I am just wondering how can I use it to do multiple words autocomplete.

e.g. INPUT rails, gem it should generate auto-list twice.

How to solve this problem?..

like image 956
ethan Avatar asked Aug 01 '10 16:08

ethan


2 Answers

rails3-jquery-autocomplete now supports specifying a delimiter using the data-delimiter option so you no longer need to hack it:

f.autocomplete_field :tags, autocomplete_tag_business_path, :"data-delimiter" => ','

I discovered it while trying to apply the hack above and discovered it isn't necessary. Works great for me!

like image 137
ToddH Avatar answered Nov 05 '22 12:11

ToddH


rails3-jquery-autocomplete plugin? It seems that it doesn't support multiple autocomplete, you need to modify the plugin code!! If you insist on your former ideas, follow my steps.

  1. run bundle show rails3-jquery-autocomplete to get the plugin working directroy
  2. mate /lib/autocomplete.rb
  3. modify the define_method like this:

    define_method("autocomplete_#{object}_#{method}") do
      arr = params[:term].split(",")
      unless params[:term] && params[:term].empty?
        items = object.to_s.camelize.constantize.where(["LOWER(#{method}) LIKE ?", "#{arr[arr.size-1]}%"]).limit(limit).order(order)
      else
        items = {}
    end
    
    render :json => json_for_autocomplete(items, method)
    

    end

  4. modify autocomplete-rails.js like this function split(val) { return val.split(/,\s*/); } function extractLast(term) { return split(term).pop(); } $(document).ready(function(){ $('input[autocomplete]').each(function(i){ $(this).autocomplete({ source: $(this).attr('autocomplete'), focus: function() { return false; }, select: function(event, ui) { var terms = split( this.value ); // remove the current input terms.pop(); // add the selected item terms.push( ui.item.value ); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(","); return false; } }); }); });

  5. restart your server and try

!! remember you'd better backup autocomplete.rb to avoid overwrite after you run bundle install.

Good luck!

like image 6
VvDPzZ Avatar answered Nov 05 '22 10:11

VvDPzZ