aronccs aronccs - 2 months ago 18
Javascript Question

Bootstrap Passing Data to a Modal

I have read the Bootsrap documentation and even tested their "Varying modal content based on trigger button" example, but that doesn't work.

Any idea on how can I pass a data to a modal so that I will not create multiple modals in my page.

Here is the button that triggers the modal:

<a class="btn btn-danger" data-toggle="modal" data-target="#deleteSubject" data-whatever="<?= $subj_id ?>" role="button" title="Delete Subject"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>


And here is the modal:

<div class="modal fade" id="deleteSubject" tabindex="-1" role="dialog" aria-labelledby="deleteSubjectLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="#" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="deleteSubjectLabel">Delete Subject</h4>
</div>
<div class="modal-body">
<h4>Do you want to delete this subject?</h4>
<input type="text" id="subjid" name="subjid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
</form>
</div>
</div>
</div>


And here is the javascript:

<script>
$('#deleteSubject').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
var subjId = button.data('whatever')
var modal = $(this)
modal.find('.modal-body input').val(subjId)
})
</script>


I also tried the
show.bs.modal
but nothing happens. I tried to create a separate script to test if the
$subj_id
is being read through the use of
alert
but it works.

Any ideas?

Answer

you need to wrap the code in a document ready and since your input is named and has an id - target it directly and then you wont need the find either:

<script>
    $(document).ready(function(){
        $('#deleteSubject').on('show.bs.modal', function (event) {
          var button = $(event.relatedTarget);
          var subjId = button.data('whatever');
          $('#subjid').val(subjId);
        })
    })
</script>