Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a JavaScript function from an erb template?

If you define a JavaScript function and then call it from an erb template the function does not get called. Why? Clicking this link should show an alert, but it does not.

= link_to "Add Sprout", new_sprout_path, remote: true

Controller:

def new
  @sprout = Sprout.new
  respond_to { |format| format.js }
end

Then in the template I call a function:

# sprouts/new.js.erb
doSomething();

The function is defined in my js files:

# javascripts/sprouts.js.coffee
doSomething = ->
  alert "yum ghum I am a new sprout."

The JavaScript comes back. I can see it in the console. But I see no alert. Why doesn't this not work?

I'm using Rails 4.

like image 692
Jumbalaya Wanton Avatar asked Dec 10 '25 21:12

Jumbalaya Wanton


1 Answers

@doSomething = -> alert "yum ghum I am a new sprout."

or

window.doSomething = -> alert "yum ghum I am a new sprout." # I prefer this approach, as it's more explicit.
like image 55
pdoherty926 Avatar answered Dec 13 '25 09:12

pdoherty926



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!