Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=""/>     </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?)

like image 823
Leon Cullens Avatar asked May 16 '12 21:05

Leon Cullens


People also ask

How do you pass data into modal?

Data can be passed to the modal body from the HTML document which gets displayed when the modal pops up. To pass data into the modal body jquery methods are used. jQuery is similar to JavaScript, however jQuery methods are simple and easier to implement. jQuery reduces the lines of code.


1 Answers

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>&nbsp;</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'); }); 
like image 60
mg1075 Avatar answered Sep 18 '22 12:09

mg1075