Blog

Load remote Rails links and forms in Bootstrap modals

As a heavy user of Bootstrap modals and Rails, I often want to use remote links or forms in a modal and load the result into the same modal. After doing this in several projects I worked on, I now copy and paste the helper directly into any new project I start that will use modals:

$(document).on 'ajax:success', '.modal [data-remote="true"]', (_, data) ->
  $(this).parents('.modal-body')
    .html(data)
    .animate
      scrollTop: 0
      , 300

The trick is to specify only [data-remote="true"], not a[data-remote="true"] or form[data-remote="true"] so it works with remote links and forms. As you see, I also added a animation that scrolls to modal to the top after inserting the new content.

This helper works with Bootstrap 2.x and 3.x.

Discuss this post on Hacker News

Ideas? Constructive criticism? Think I'm stupid? Let me know in the comments!