2

I have a menu item that fires ajax that returns javascript partial that is a bootstrap modal. The problem I am having is when a user clicks the menu item the first time, the modal opens as expected. The user closes the modal and tries to open it again, it doesn't open (although the ajax fires again from backend).

Consider the following code (using bootstrap 4):

Menu.html.erb:

<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
    <%= link_to user_profile_path(current_user.user_profile.id), remote: true, class: "dropdown-item" do %>
        <%= fa_icon "id-card", text: "Profile Settings" %>
    <% end %>
</div>
...
<div id="user_profile"></div>

user_profile/show.js.erb (ajax js partial):

$("#user_profile").replaceWith("<%= j render "user_profile" %>");

user_profile/_user_profile.html.erb (bootstrap modal):

<script>
    $('#user_profile_modal').modal('show');
</script>

<%= form_with model: @user_profile do |f| %>
    <div class="modal fade" id="user_profile_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
        ...
        </div>
    </div>
<% end %>

Is there a way to fire the the modal('show'); each time the modal is fired from the backend? By the way, this is just one of 3 modals that get loaded this way on the page.

Thanks again!

1 Answer 1

2

After trying a few things, simply replacing the replaceWith with html in the user_profile/show.js.erb will cause the ajax to fire each time.

Old:

$("#user_profile").replaceWith("<%= j render "user_profile" %>");

New:

$("#user_profile").html("<%= j render "user_profile" %>");

The reason for this is because the replaceWith is replacing the element in the parent, and thus not firing again because the element has already been replaced the first time.

Hope that helps anyone in the future!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.