I find an easy and I think better way in the bootstrap official website:
Using data- attribute.
I show it with an working example for who that could not achieve better solution:
Suppose we want to fill a table body with some data (as my problem):
PHP Code:
//just table body code
<tbody>
<?php foreach($fields as $field): ?>
<tr>
<td><?php $field->some_field; ?></td>
//other <td> elements
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"
data-time="<?php echo $field->time; ?>">Show Details</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
So in a loop, I read data (that in controller, get with model's method, and pass to view with $data['
fields']). Now for showing some details in modal, I use
HTML5 data attribute. Suppose, I want to show
time in the modal. As you see in above code, I put time field in data-time:
data-time="
<?php echo $field->time; ?>"
Now I create a modal as
template (you could see whole modal structure in bootstrap official website) and put it out of loop (one modal for all table rows; dynamic data). in the following code, I put an element in the modal body (as a placeholder):
Code:
//... in the modal body section
<h4 id="time"></h4>
This element have no content, because I want to retrieve every row time filed and put it in this element. Note this will be practical with defining an id. Now some script:
Code:
//first load jquery
<script type="text/javascript">
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function(event){
var btn = $(event.relatedTarget);
var time = btn.data('time');
$('#time').text(time);
});
});
</script>
first,
find which button is clicked (
var btn = $(event.relatedTarget);)
second,
get the time data attribute (
var time = btn.data('time');)
and then
put the data value in the element which set in the modal with an id (
$('#time').text(time);)
You could define more data attribute and retrieve in this way.