How to Display Selected Item in Bootstrap Button Dropdown Title
As far as i understood your issue is that you want to change the text of the button with the clicking linked text, if so you can try this one: http://jsbin.com/owuyix/4/edit
$(function(){
$(".dropdown-menu li a").click(function(){
$(".btn:first-child").text($(this).text());
$(".btn:first-child").val($(this).text());
});
});
As per your comment:
this doesn't work for me when I have lists item <li>
populated through ajax call.
so you have to delegate the event to the closest static parent with .on()
jQuery method:
$(function(){
$(".dropdown-menu").on('click', 'li a', function(){
$(".btn:first-child").text($(this).text());
$(".btn:first-child").val($(this).text());
});
});
Here event is delegated to static parent $(".dropdown-menu")
, although you can delegate the event to the $(document)
too because it is always available.
Updated for Bootstrap 3.3.4:
This will allow you to have different display text and data value for each element. It will also persist the caret on selection.
JS:
$(".dropdown-menu li a").click(function(){
$(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
$(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});
HTML:
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#" data-value="action">Action</a></li>
<li><a href="#" data-value="another action">Another action</a></li>
<li><a href="#" data-value="something else here">Something else here</a></li>
<li><a href="#" data-value="separated link">Separated link</a></li>
</ul>
</div>
JS Fiddle Example