ruby on rails call javascript function from button_tag



I am trying to perform a very simple task: Button is clicked – message is displayed (via JavaScript). Most likely I am either looking in the wrong places or going completely wrong about it but I can’t find any examples that will show how to accomplish this simple task.

My js function is:

function myAlert() {
     alert ("My Message")
       }

The button_tag is:

<%= button_tag "Save Changes", :onclick => "myAlert()"%>

I would like to know how to properly call the function with button_tag, and where this function should be placed in the Rails app, e.g., application.js or some other file.

Answer

Well, You are doing it in a right way already. This is a simpler and cleaner way to code. To find javascript easily you should place your js code in assets/javascripts/[file_name] where file_name is generated on the bases of your model name by generate method of rails cli.



Source: stackoverflow