dimanche 22 mai 2016

Migrate Javascript to CoffeeScript and make it work on page load

I am attempting to have a javascript to be loaded for a field's class. Here is my view:

<%= form_for @game do |f| %>
  <div class="row">
    <div class="col-lg-4 col-md-6">
      <div class="form-group">
        <%= f.label :time %>
        <%= f.text_field :time, class: 'form-control form-datetime', readonly: true %>
      </div>
    </div>
  </div>
<%= f.submit(class: 'btn btn-success')%>
<% end %>

<script>
  $(".form-datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii'})
</script>

I can only get the javascript to work on page refresh. On the first load, the page console states:

Uncaught TypeError: $(...).datetimepicker is not a function

On page reload it works fine.

I have attempted to use the document ready handler as so, with no luck:

<script>
  $( document ).ready(function() {
    (".form-datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii'});
  });
</script>

I would also like to remove this <script> tag from the view and place it in the CoffeeScript file. What do I need to write in the CoffeeScript file to load this java function on first page load?

Aucun commentaire:

Enregistrer un commentaire