Skip to content

Instantly share code, notes, and snippets.

@Matho
Forked from henkm/gist:952240
Last active December 18, 2015 17:50
Show Gist options
  • Save Matho/5821770 to your computer and use it in GitHub Desktop.
Save Matho/5821770 to your computer and use it in GitHub Desktop.
Jquery Tokens - custom tokens on the fly
Use this fork https://github.com/kusmierz/jquery-tokeninput/
See this discussion about idea http://railscasts.com/episodes/258-token-fields?view=comments#comment_152978
#model (idea 100% stolen from ryanb)
def author_tokens=(ids)
ids.gsub!(/CREATE_(.+?)_END/) do
Author.create!(:name => $1).id
end
self.author_ids = ids.split(",")
end
# jquery.tokeninput.js
# line 598, change this line:
# var this_token = settings.tokenFormatter(item)
# to this:
# var this_token = settings.tokenFormatter(item).replace('Add: ', '');
# comment line 1028 to
# //if(settings.allowCustomEntry == false) {
# and also comment ending bracket to
# //}
# add allowCustomEntry: true to your book_author_tokens.js file
$(function() {
$("#book_author_tokens").tokenInput("/authors.json", {
crossDomain: false,
prePopulate: $("#book_author_tokens").data("pre"),
theme: "facebook",
allowCustomEntry: true
});
});
# controller
def index
@authors = Author.where("name like ?", "%#{params[:q]}%")
results = @authors.map(&:attributes)
results << {:name => "Add: #{params[:q]}", :id => "CREATE_#{params[:q]}_END"}
respond_to do |format|
format.html
format.json { render :json => results }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment