Leon Cullens Leon Cullens - 5 months ago 66x
Javascript Question

Passing data to a bootstrap modal

I've got a couple of hyperlinks that each have an ID attached. When I click on this link, I want to open a modal ( http://twitter.github.com/bootstrap/javascript.html#modals ), and pass this ID to the modal. I searched on google, but I couldn't find anything that could help me.

This is the code:

<a data-toggle="modal" data-id="@book.Id" title="Add this item" class="open-AddBookDialog"></a>

Which should open:

<div class="modal hide" id="addBookDialog">
<div class="modal-body">
<input type="hidden" name="bookId" id="bookId" value=""/>

With this piece of code:

$(document).ready(function () {
$(".open-AddBookDialog").click(function () {

However, when I click the hyperlink, nothing happens. When I give the hyperlink a href="#addBookDialog", the modal opens just fine, but it does't contain any data.

I followed this example: How to pass values arguments to modal.show() function in twitter bootstrat

(and I also tried this: How to set the input value in a modal dialogue?)


I think you can make this work using jQuery's .on event handler.

Here's a fiddle you can test; just make sure to expand the html frame in the fiddle as much as possible so you can view the modal.



<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>


<p>Link 2</p>
<a data-toggle="modal" data-id="ISBN-001122" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<div class="modal hide" id="addBookDialog">
 <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
    <div class="modal-body">
        <p>some content</p>
        <input type="text" name="bookId" id="bookId" value=""/>


$(document).on("click", ".open-AddBookDialog", function () {
     var myBookId = $(this).data('id');
     $(".modal-body #bookId").val( myBookId );
     // As pointed out in comments, 
     // it is superfluous to have to manually call the modal.
     // $('#addBookDialog').modal('show');