Mark Locklear
Mark Locklear

Reputation: 5325

Rails tokenInput values not reloading

I have implemented a token input field in my Rails 3 app. Here is the relevant code:

my form

<%= label_tag :tag_tokens, 'Tags' %>
<%= text_field_tag 'tag_tokens', "data-pre" => params[:tag_tokens] %>

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

This is a search page that returns results. The token input along with the values returned work wonderfully. The issue I am having is getting the values to remain/load in the text box after the page is submitted. The "data-pre" => params[:tag_tokens] code in the text_field_tag should handle this but no worky! Any help appreciated.

Upvotes: 1

Views: 94

Answers (1)

Mark Locklear
Mark Locklear

Reputation: 5325

I found my issue was I am using text_field_tag (not text_field) there for I needed to pass data-pre as the 3rd parameter (not the 2nd). Here is all my code for posterity.

view

<%= label_tag :tag_tokens, 'Tags' %>
<%= text_field_tag 'tag_tokens', nil, "data-pre" => @tag_token_names.to_json %>

js

$(function() {
    $("#tag_tokens").tokenInput("/data/tags.json", {
      crossDomain: false,
      prePopulate: $("#tag_tokens").data("pre"),
      theme: "facebook"
    });
});
</script>

routes

match "/tags" => "data#tags", :as => 'tag_token_search'

controller

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

Upvotes: 1

Related Questions