How to use js file within view folder

一曲冷凌霜 提交于 2019-12-04 14:15:33

Looking at your code

$('#submit').on('click', function(){  
 $('#lol').append("<%= escape_javascript(render :partial => 'myPartial' ) %>");
} 

I think you are confusing between ajax and normal jquery. If you don't need to perform anything else then you should use normal jquery to show and hide your content. For that you need to put this code in your app/assets/javascript/application.js or make a new file then require it inside application.js like

//= require file_name

Inside your view you can hide the parent element of your content by giving it a style like this:

#your_content_container{
  display: none;
}

Then place your jquery code in your_file.js

$(document).on("click","#submit",function(){
  $("##your_content_container").show();
})

If it's a form as your question says then you need to to perform some logic in your controller too so you should use Ajax

Since it's a form so you need to use remote: true option in your form something like:

<%= form_for(@user, remote: true) do |f| %>
  // your fields
<% end %>

and then inside your controller you can have

def your_method
  #do your logic here
  respond_to do |format|
    format.js{}
  end
end

This will allow rails to look for a file named your_method.js.erb in your views where you can call your jquery and render your partial. In your_method.js.erb

$('#lol').append("<%=j render :partial => 'myPartial' %>");

For details refer to Working with Javascript in Rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!