Activate AJAX action on button click inside dropdown menu without closing it


As you probably know, any action inside twitter bootstrap causes the dropdown to close, except for use cases:

$('.dropdown-menu').click(function(event){
         event.stopPropagation();
      })

      

Unfortunately it event.stopPropagation()

also stops the ajax request.
what i want to achieve is something like when you get a friend request on FB and you accept / reject inside the dropdown without closing it.
Can you help me?

+3


source to share


1 answer


Just place the ajax call after the call event.stopPropagation

.

In this case, the click must be on the element $('.dropdown-menu > li > a')

. See example below.



/**** Ignore this command - just used to mock up an ajax response **/
$.mockjax({
  url: '/likethis',
  responseTime: 1000,
  responseText: {
    status: 'success',
    fbStatus: 'liked'
  }
});

$('.dropdown-menu > li > a').click(function(event){
    event.stopPropagation();
  
    $.ajax({ url: '/likethis',
              success: function() {
                 $('#likelink').html('<span class="glyphicon glyphicon-ok"></span> Liked!');
              }
           });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/1.5.3/jquery.mockjax.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

<!-- Single button -->
<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Like This <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#" id="likelink">Like</a></li>
  </ul>
</div>
      

Run codeHide result


+1


source







All Articles