jquerybootstrap-modal

Jquery passing data attributes to modal on click link


I am trying to pass some custom data attributes to a modal which is opened through a link .

The HTML snippet is as following:

<div class="btn-group">
 <button aria-expanded="false" class="btn btn-xs green dropdown-toggle" data-toggle="dropdown" id="button_action" type="button">Action <i class="fa fa-angle-down"></i></button>
  <ul class="dropdown-menu" role="menu">
     <li>
         <a id="modal_contact" data-userName="User1" data-toggle="modal" href="#option_contact">
         <i class="fa fa-check-square-o"></i> Contact</a>
     </li>
</ul>
</div>

The modal snippet is as following :

<div class="modal fade" data-backdrop="static" data-keyboard="false" id="option_contact" tabindex="-1">
 <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button aria-hidden="true" class="close" data-dismiss="modal"
            type="button"></button>
            <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
        </div>
    </div>
 </div>
</div>

I seem to be unable to set "modal-title" with the value of attribute "data-userName".

The jquery I thought would do so (only inserted alert to see if value is passed or not) :

$('#modal_contact').on('click', function() {
  var $el = $(this);
  var $username = $el.data('userName');
    alert(username);
  });

But it does not seem to work. What would be the proper approach to this ?


Solution

  • Try using bootstrap modal's event callbacks instead of click handler:

    $('#option_contact').on('shown.bs.modal', function() {
      var $el = $("#modal_contact");
      var $username = $el.data('userName');
      alert(username);
    });