0

I'm trying to implement some JavaScript in my Rails 6 app, I have no idea if I'm going about it the right way but so far everything I've tried has been wrong.

I have a file javascripts/form_helpers/submit.js for now it just looks like this:

const submit_action() {
  console.log("hello world");
}

In javascripts/application.js I have

require("form_helpers"); 
# I've also tried require("form_helpers/submit.js") but I thought I could just include the directory which seems to be what Rails ships with for channels

Then in the actual view I have a form_with tag:

  <%= submit_tag 'Submit', class: "button button-create button-log-radius", onclick: "submit_action()" %>

I always get a reference error when I click the submit button that submit_action is not defined. Am I on the right track here? Am I way off base? I'm a little confused by this new javascript folder, am I using it right or should I be putting scripts like this into the assets directory?

BTW I've seen this question asked before on here and the answer had to do with appending window before your function name (here) but that feels hacky to me.

tfantina
  • 788
  • 11
  • 37
  • Can you check if the javascript has loaded in browser? If yes, put a debugger and see if the control is reaching the submit_action() method. – Akshay Kumar Jan 10 '20 at 05:52
  • If I change the sbumit.js function to: `debugger; const submit_action() { console.log("hello world"); }` it will pause the browser when the page loads but will still say "uncaught reference error, submit_action not defined" – tfantina Jan 10 '20 at 13:52
  • Do you see the submit.js in developer tools -> sources when the page is loaded or when the debugger is hit? – Akshay Kumar Jan 10 '20 at 14:09
  • Yeah, when the debugger pauses the page the entirety of submit.js shows. – tfantina Jan 10 '20 at 14:11
  • Try this: Adding the js file in app/javascript/packs In the end of application.html.erb file add this <%= javascript_pack_tag 'custom', 'data-turbolinks-track': 'reload' %> Next, rake assets:precompile – Akshay Kumar Jan 10 '20 at 14:24
  • Thanks for sticking with me on this. Unfortunately, no luck, the debugger will still pause if I leave it in but then it says submit_action is not defined. – tfantina Jan 10 '20 at 14:41
  • Don't mention. Were you able to figure out what caused the issue? – Akshay Kumar Jan 15 '20 at 15:38
  • Thanks for following up, I never got it working. this is just a personal project so I just switched to another branch and started working on some other things. – tfantina Jan 16 '20 at 02:03

0 Answers0