Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a modal for one entry in a .each loop - Rails / Bootstrap

I'd like a link to open a modal displaying the clicked object (word.title), displayed in an each loop. Right now it opens the modal but then displays it again for every item in the loop.

    <h1>Glossary of words</h1>
    <p>Pagination at 25</p>

    <table class="table table-hover">
        <thead>
            <tr>
                <th>Title</th>
                <th>Definition</th>
                <th>Usage</th>
                <th>Word Type</th>
            </tr>
        </thead>
        <tbody>
        <% @words.each do |word| %>
            <tr>
                <th scope="row">
                    <a href="#" data-toggle="modal" data-target=".bs-example-modal-sm">
                        <%= word.title %>
                    </a>
                        <div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
                          <div class="modal-dialog modal-sm">
                            <div class="modal-content">
                              <%= word.title %>
                            </div>
                          </div>
                        </div>
                </th>
                <td><%= word.title %></td>
                <td><%= word.definition %></td>
                <td><%= word.word_type %></td>
            </tr>

        <% end %>
        </tbody>
    </table>

// Word Modal
$('.bs-example-modal-sm').modal()

1 Answers

To make your links call the correct modal, you need to assign id to eachmodals. And use data-target attribute to call a modal by passing the id of modal in to it.

And you code might look like this.

<a href="#" data-toggle="modal" data-target="#modal-<%= word.id %>">
    <%= word.title %>
</a>

<div id="modal-<%= word.id %>" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm">
    <div class="modal-content">
      <%= word.title %>
    </div>
  </div>
</div>

source: http://getbootstrap.com/javascript/#live-demo

like image 112
mininoz Avatar answered Dec 09 '25 22:12

mininoz