I have 2 pieces of code that will only run once when I make a change and save the code in the form and then reload the form. The next time I open and run the form it fails to run. Every other part of my application runs just fine.
The first is a datepicker:
The datepicker only shows up the first time.
Here is the coffee script:
$.fn.extend {
integrateDatepicker: (selector)->
selector = selector || '.datepicker'
$(@).find(selector).datepicker({"format": "dd/mm/yyyy"})
}
$(document).ready () ->
$('body').integrateDatepicker()
Here is the form snippet:
<div class="row">
<div class="span6 offset3">
<%= simple_form_for([@council_report]) do |f| %>
<p>
<%= f.input :report_title %>
</p>
<p>
<%= f.input :report_desc %>
</p>
<p>
<%= f.input :report_date, as: :string, input_html: {class: 'datepicker'} %>
</p>
<p>
<%= f.submit class: "btn btn-large btn-primary" %>
</p>
<% end %>
</div>
</div>
The second is a form post:
The "create" action runs successfully only the first time the form loads.
Here is the form snippet:
<%= form_for(:select_asset, url: {action: "create"}) do |form| %>
<% @assets_not_in.each_with_index do |asset_not_in, index|
asset = Asset.find(asset_not_in.id) %>
<%= fields_for "assets_to_check[#{index}]", asset_not_in do |f| %>
<%= f.hidden_field :id, :value => asset.id %>
<tr>
<td><%= asset.asset_name %></td>
<td><%= asset_type_desc(asset.asset_type_code) %></td>
<td><%= asset.address.address_long %></td>
<td><%= asset.address.postcode %></td>
<td><%= asset.address.state_code %></td>
<td><%= f.check_box :add_asset %></td>
</tr>
<% end %>
<% end %>
</table>
<%= link_to 'Back', council_report_report_assets_path(@council_report) %>
<%= form.submit "Add Assets", class: "btn btn-large btn-primary" %>
<% end %>
Questions:
Turbolinks is enabled by default in rails 4 and will cause issues with jQuery's $(document).ready
.
To verify you're runnign turbolinks, check your app/views/layouts/application.html.erb
. Look for the lines
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
in the head
. If they are set to true, try adding the jquery-turbolinks
gem to your Gemfile.
Turbolinks renders some parts of the page via ajax, so $(document).ready
will not fire unless you enter the site through that page OR do a hard refresh. The gem fixes this by automatically changing your $(document).ready
listeners: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.