Ben Ben - 10 days ago 4x
Javascript Question

How to load image into bootstrap modal with javascript

My setup is 4 links (below). I want each link to open myModal, but depending on which link gets clicked, a different image file should load in the modal. I got it working for one of the links.

<li><a href="#myModal" data-toggle="modal">6 Teams</a></li>
<li><a href="#">5 Teams</a></li>
<li><a href="#">4 Teams</a></li>
<li><a href="#">3 Teams</a></li>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="width:800px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-body">
<img src="/images/brackets/6teamDouble1.jpg">
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>

How do I get this to work for each link without building a separate modal for each one?


By using jquery .click you can easily achieve this (with html5 data attribute too).

    <li><a href="#myModal" data-toggle="modal" data-img-url="">6 Teams</a>
    <li><a href="#myModal" data-toggle="modal" data-img-url="">5 Teams</a>
    <li><a href="#myModal" data-toggle="modal" data-img-url="">4 Teams</a>
    <li><a href="#myModal" data-toggle="modal" data-img-url="">3 Teams</a>


$('li a').click(function (e) {
    $('#myModal img').attr('src', $(this).attr('data-img-url'));


Note: Though you did not specify using jQuery, twitter-bootstrap modal require you to use jQuery anyway, so might as well use it.