Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show twitter bootstrap modal via JS request in rails?

I want to show a twitter bootstrap modal as a response to a JS request. My show.js.erb function looks something like this:

$(document).ready(function() {

    $('#dialog').modal('show')

});

Here "dialog" is the modal's id. The modal code itself looks something like this:

<div id="dialog" class="modal hide fade">
    <div class="modal-header">
          <a href="#" class="close">&times;</a>
          <h3> Showing Modal </h3>
    </div>
    <div class="modal-body">
        I need to show up!
    </div>
    <div class="modal-footer">
        <a href="#" class="btn primary">Done</a>
    </div>
</div>

One thing I am sure of is that the javascript is being called. I can have it alter items on the page. Another thing is that modal is working fine. It shows up just fine when I use an HTML button to trigger the request like this:

<button data-controls-modal="dialog" data-backdrop="true" data-keyboard="true" class="btn danger"> Show </button>

Any idea why the modal doesn't show up on JS request?

Thank You!

like image 340
Yusuf Saber Avatar asked Dec 16 '11 03:12

Yusuf Saber


2 Answers

I had a similar problem, which I solved with a slight twist

My modal div is rendered on the calling page (from a partial) and not by the response of the JS request:

<div class="modal hide fade" id="modal-window">
  <div class="modal-header">
    <a href="#" class="close">×</a>
    <h3>Loading...</h3>
  </div>
  <div class="modal-body center">
      <%= image_tag "loading.gif" %>
  </div>
  <div class="modal-footer">&nbsp;</div>
</div>

I use this link to rely on rails and Twitter unobtrusive JS:

<%= link_to negotiation.name, negotiation_path(negotiation), {:remote => true, 'data-controls-modal' =>  "modal-window", 'data-backdrop' => true, 'data-keyboard' => true} %>

and my show.js.erb looks like this (shortened)

$('.modal-body').html('<%= escape_javascript(render :partial => 'negotiationdetail', :object => @negotiation) %>');
$('.modal-header').remove(); // don't need a header here

This works fine and has the benefit of showing a "loading" animation to the user while the modal is being populated.

like image 87
Pierre Avatar answered Oct 10 '22 17:10

Pierre


I had this problem and i fixed it by changing the javascript rendering to:

    $("#modal-window").find(".modal-content").html("<%= j (render 'new') %>");
    $("#modal-window").modal();

And the modal window to:

    <div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content"></div>
      </div>
    </div>

You can check more detailed explanation here https://kolosek.com/rails-creating-modals

like image 25
Nesha Zoric Avatar answered Oct 10 '22 19:10

Nesha Zoric