DEV Community

Robert
Robert

Posted on

2 1

How to add Ajax functionality to a form for replacing a DOM element with a partial?

How to add Ajax functionality to a form for replacing a DOM element with a partial?

Add to form remote: true or refactor to form_with

In your controller action, e.g. foobar, add:

def foobar

  respond_to do | format |
    format.js
    format.html
  end

end
Enter fullscreen mode Exit fullscreen mode

Create the same file name as the controller action:

foobar.js.erb

Content of foobar.js.erb:

$("#id").replaceWith("<%= j render('partial_name') %>");

Perhaps possible to extract partial from current view

_partial_name.html.erb

Add this back in the view with

<%= render "partial_name" %>

Done.

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay