Dynamically Load content in bootstrap modal

<!-- this is the table that shows the user information -->
<table class="zebra-striped">
	<thead>
		<tr>
			<th>#</th>
			<th>First Name</th>
			<th>Last Name</th>
			<th>Email</th>
		</tr>
	</thead>
	<tbody>
		<?php
		$fields = array('id','first_name','last_name','email');
		foreach ($data as $user) { ?>
		<tr data-href="/users/edit/<?php echo $user->id; ?>/1">
			<?php foreach ($fields as $field) { ?>
			<td><?php echo $user->$field; ?></td>
			<?php } ?>
		</tr>
		<?php } ?>
	</tbody>
</table>

<!-- this is the placeholder for the modal box -->
<div id="modal-editUser" class="modal hide">
	<!-- content will go here -->
</div>

<!-- this is the code that makes it all happen -->

<script type="text/javascript">
	jQuery( function($) { 
		// find all tr's with a data-href attribute
		$('tbody tr[data-href]').click( function() {
			// copy the data-href value to the modal for later use
			$('#modal-editUser').attr('data-href',$(this).attr('data-href'));
			// show the modal window
			$('#modal-editUser').modal({show: true , backdrop : true , keyboard: true});
		}).find('a').hover( function() { 
			// unbind it in case I put some a tags in the table row eventually
			$(this).parents('tr').unbind('click'); 
		}, function() { 
			$(this).parents('tr').click( function() { 
				// rebind it
				$('#modal-editUser').attr('data-href',$(this).attr('data-href'));
				$('#modal-editUser').modal({show: true , backdrop : true , keyboard: true});
			}); 
		});

		// when the modal show event fires, load the url that was copied to the data-href attribute
		$('#modal-editUser').bind('show', function() {
			$(this).load($(this).attr('data-href'));
		});
	});
</script>
Advertisements

One thought on “Dynamically Load content in bootstrap modal

  1. The same can also be achieved alternatively

    Launch Modal

    Now you need the HTML DIV where modal content will be loaded. With remote data, you only need it in one place within your application, for example, in Rails you can put it to a layout file. Of course, this would mean the remote page you are loading has the correct Twitter Bootstrap modal markup (check an example on their site).


    Then, add the actual jQuery spice to your JavaScripts (CoffeeScript syntax):

    ($ "a[data-toggle=modal]").click ->
    target = ($ @).attr('data-target')
    url = ($ @).attr('href')
    ($ target).load(url)

    That’s it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s