Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Token Input only works once i refresh the page

So when i first go to a page where i use TokenInput, the tokeninput never hits my input form. Only after i refresh the page it works. Why is this and how can i make it work when i initially go the page?

When i first go to my page. Look at players field.

enter image description here

Once i refresh

enter image description here

I guess something happens to the javascript. Upon looking into the issue, it seems like the whole page loads with correct data for the date fields and checkbox. After i refresh the correct data appears in my token input as it should, but with incorrect values for my checkbox and dates.

The dates and checkbox values belongs to another roster.

application.html

<%= stylesheet_link_tag    "application", "token-input-facebook", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "jquery-tokeninput", "data-turbolinks-track" => true %>

application.js

//= require jquery
//= require jquery_ujs
//= require bootsy
//= require turbolinks
//= require_tree .
//= require twitter/bootstrap
//= require jquery_nested_form

});

$(function() {
  $("#roster_player_tokens").tokenInput("/players.json", {
    crossDomain: false,
    prePopulate: $("#roster_player_tokens").data("pre"),
    theme: "facebook",
    propertyToSearch: "gamertag",
    hintText: "Type in a gamertag",
    searchingText: "Searching...",
    tokenLimit: 4,
    preventDuplicates: true
  });
});

My rosters form

<%= form_for([@team, @roster]) do |f| %>
  <% if @roster.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@roster.errors.count, "error") %> prohibited this roster from being saved:</h2>
      <ul>
      <% @roster.errors.full_messages.each do |msg| %><li><%= msg %></li><% end %>
      </ul>
    </div>
  <% end %>
  <form role="form">

    <%= f.label :current %><br>
    <%= f.check_box :current %><br>

    <%= f.label :start %><br>
    <%= f.date_select :start %><br>

    <%= f.label :end %><br>
    <%= f.date_select :end, {:include_blank => true, :default => nil} %><br>

  <%= f.label :player_tokens, "Players" %><br />
  <%= f.text_field :player_tokens, "data-pre" => @roster.players.map(&:attributes).to_json %><br>

  <%= f.submit :class => "btn btn-warning" %>
  </form>

<% end %>
like image 833
Pierre Avatar asked Jan 24 '26 05:01

Pierre


1 Answers

If this was plain jQuery, then the $.tokenInput() function would need to be wrapped in $(document).ready().

I'm not a rails user, but something similar should be done here also. The OP stated he "put [the] script in [the] html file instead of application.js", which did the job.

like image 63
Chris Avatar answered Jan 26 '26 21:01

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!