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=""/>
</div>
</div>
With this piece of code:
$(document).ready(function () {
$(".open-AddBookDialog").click(function () {
$('#bookId').val($(this).data('id'));
$('#addBookDialog').modal('show');
});
});
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 Bootstrap
(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.
http://jsfiddle.net/Au9tc/605/
HTML
<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> </p>
<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>
<div class="modal-body">
<p>some content</p>
<input type="text" name="bookId" id="bookId" value=""/>
</div>
</div>
JAVASCRIPT
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
// As pointed out in comments,
// it is unnecessary to have to manually call the modal.
// $('#addBookDialog').modal('show');
});