问题
Hi I've tokenInput documentation but somehow my text_field category_tokens is not prepopulated with categories while editing.
Here are code snippets
<input id="product_category_tokens" type="text" size="30" name="product[category_tokens]" data-pre="[{"created_at":"2010-09-13T03:33:17Z","description":"","id":x,"name":"Kitchen & Dining ","parent_id":xx,"permalink":"kitchen-dining","updated_at":"2011-01-05T11:17:10Z"}]" style="display: none;">
$(function() {
$("#product_category_tokens").tokenInput("/categories.json", {
crossDomain: false,
prePopulate: $('#product_category_tokens').data('pre'),
preventDuplicates: true
});
});
<%= f.text_field :category_tokens, "data-pre" => @product.categories.map(&:attributes).to_json %>
Any pointer is appreciated!
回答1:
Maybe you can try to change your prePopulate
to $(this).data("pre")
.
Another tip is to use field class instead of id in the JS function and in your view since it changes when rendered.
Hope it help you.
回答2:
change
<%= f.text_field :category_tokens, "data-pre" => @product.categories.map(&:attributes).to_json %>
to
<%= f.text_field :category_tokens, input_html => { "data-pre" => @product.categories.map(&:attributes).to_json } %>
回答3:
Json should return objects not as string this will convert string to Json object
JSON.parse(tokendata)
来源:https://stackoverflow.com/questions/6368921/jquery-tokeninput-not-prepopulating-the-text-field