Search code examples
jquerytwitter-bootstrapgsp

pass and check parameters in bootstrap modal


I have a bootstrap modal that is triggered by two links in the same page and i want to pass some parameter that inform the dialog from which element it has been triggered. so i can check this parameter in my dialog gsp tempalte.

first link

 <a href="#" id="editCourseModal" data-toggle="modal" data-target="#createCourseModal" data-backdrop="static" data-keyboard="false">

second one button:

<button type="button" class="form-group btn btn-md btn-default" 
   data-toggle="modal" data-target="#createCourseModal" data-backdrop="static" data-keyboard="false">

modal dialog:

<div id="createCourseModal"  tabindex="-1" role="dialog" arialabelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body edit-content">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

I want to check this parameter in my dialog ( g:if test="this parameter" ) so i can implement, hide and show some html elements based on this. is it possible to do that? has anyone some other idea to solve this issue otherwise?


Solution

  • You can add a data attribute to each of the trigger buttons with the parameter you want to send through and do something like

    $('#createCourseModal').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget) // Button that triggered the modal
    
      var parameter = button.data('yourDataAttributeName') // Extract info from data-* attributes
    
      var modal = $(this)
      if (parameter == X) {
          modal.find('.modal-title').text('Clicked by X');
      } else {
          modal.find('.modal-title').text('Clicked by Y');
      }
    })