How to return javascript after a form submission using hotwire?
-
Rails 6.1 with hotwire.
-
I want to change the color of the button of a form after it has been submitted. There is no need for this to be broadcasted to all users.
<%= form_with url: post_path, local: false do |form1| %>
<%= form1.submit “Submit!” %>
<% end %>
I want to return the following javascript:
// create.js.erb
alert("hello world!");
# controller.rb
def create
respond_to do |format|
format.js # how do i invoke and run the js above
# etc
end
Was wanting to know if this could be done somehow? I simply want to change the color of the form button after a successful form submission.
any pointers would be much appreciated. thank you!
you can use the a stimulus controller for that. in the Hotwire screencast explain how to reset a form after submit. you can create a similar stimulus controller to change the color of the button after submit.
1 Like
derencius Thank you for your solution - that will certainly solve this particular problem.
But was wondering, if server generated JavaScript is possible while still using hotwire (turbo drive)?
I’ve been replacing all .js.erb files with turbo and stimulus. I haven’t had the need to mix both solutions.
The server is returning your rendered html content or turbo-stream commands for simple html replacement.
We should strive to stop returning json or js! Embrace stimulus controllers to cleanly organize your javascript. You can add the data attributes to your html returned from the server, so as soon as turbo inserts that new html, stimulus will attach the controllers to the tags.
2 Likes
@leehericks @derencius thanks for your comments. so i take it that hotwire is fundamentally incompatible with SRJ (server rendered javascript).
chrs
1 Like
It’s a complete replacement.
1 Like