ruby-on-railsrubyjquery-tokeninputjquery-rails

Same list of entries coming railscasts tokeninput


I am using railscasts tokeninput plugin for automcomplete. I want that only those entries shown in dropdown list which are not included in input field

My JS code is

$(function() {
  $("#category").tokenInput("/products/product_categories.json", {
    crossDomain: false,
    prePopulate: $("#category").data("pre"),
    theme: "facebook"
  });
});

My controller is

def product_categories
category = Category.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
  format.html
  format.json { render :json => category.map(&:attributes) }
end

end

It works fine but the issue is same list appear each time. Lets suppose in dropdwon list there are two entries asia and africa. After adding asia to input field, again when click on field both asia and africa appear.

I want that if entry is already included in input field it must not appear in drop-down list


Solution

  • If you are using JQuery tokeinput you have 2 options to prevent duplicates

    1. Use preventDuplicates options so that even if user select same options multiple times from list it will be added only once.
    2. Use callback onResult to manipulate response data. Read content of input field and remove those items from data array. You can refer this stack overflow question to see how to write onResult callback.

    Full documentation for JQuery tokeninput is here.