简体   繁体   中英

JavaScript Rails code not working in application.js

  $(document).ready(function() { 
    $('#client-select2').select2();
   });

If i place the code above to application.js, it does not respond but if I place it in the _form.html.erb file, it does. Anyone know why that is?

views/orders/_form.html.erb

<script type="text/javascript">
  $(document).ready(function() { 
    $('#client-select2').select2();
   });

</script>

<%= simple_form_for(@order) do |f| %>
  <%= f.error_notification %>
    <%= f.input :code %>
    <%= f.association :client, collection: Client.all, label_method: :name, value_method: :id, prompt: "Choose a Client", required: true, input_html: { id: 'client-select2' } %>
    <%= f.submit %>
<% end %>

application.html.erb has

<%= javascript_include_tag 'application' %>

The reason could be that select2 and/or jQuery is included after your application.js,

If for instance, if the order is:

//=require_self
//=require select2
//=require jquery

The jquery/select2 functions will not be available in application.js since application.js is included before.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM