allegutta
allegutta

Reputation: 5644

How to get 'id' from an open bootstrap modal?

I have a modal with id="<%= p.id %>" (the id of the post that is in the modal). I want to do something with the content of the modal when it is open (and I need to do this in the.js file). But how can I get id from the opened modal into javascript?

I have tried with the javascript code under, but it does not work. Any suggestions?

_singlePost.html.erb

<a class="fg" href="#<%= p.id %>" data-toggle="modal">
    <div id="withJosefin">
        <%= p.title %>
    </div>
</a>

<div id="<%= p.id %>" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <p><h3 id="myModalLabel"><%= p.title %></h3></p>
    </div>
    <div class="modal-body">
        <%= raw(p.link) %>
    </div>
</div>

pages.js.coffee

$ ->
  if ('div.modal.hide.in').is(":visible")
    currentId = $('.modal.fade.in').attr('id')
    //Do something with currentId here

Upvotes: 2

Views: 29482

Answers (1)

Automatico
Automatico

Reputation: 12936

Found this in the documentation:

You can create a callback when the modal is shown like this:

$('#myModal').on('shown', function () {
  // do something…
})

In your case you would have this:

//Somewhere in the beginning of your coffeescript/javascript before the modal is opened by the user.

//CoffeeScript
$("div.modal.hide").on "shown", ->
    id = $(this).attr('id')
    //Do whatever you want with the id

//javascript
$('div.modal.hide').on('shown', function(){
    var id = $(this).attr('id');
    //Do whatever you want with the id
});

Hope that helps

Upvotes: 2

Related Questions