Tom Rudge Tom Rudge - 17 days ago 7
HTML Question

Display Selected Item in Bootstrap Button Dropdown Title / place holder text

This question has been asked a few times on Stackoverflow - however I still cant get to the bottom of it... plus my query is throwing more dropdowns into play. So I have two dropdowns and a search. I want to select from the dropdowns and the 'selected' to replace the dropdown place holder text. But I also need to keep in mind that after hitting search it will query a database for these selected fields.

<!-- Search box Start -->
<form>
<div class="well carousel-search hidden-phone">
<div class="btn-group">
<a class="btn dropdown-toggle btn-select" data-toggle="dropdown" href="#">Select a Country<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Item I</a></li>
<li><a href="#">Item II</a></li>
<li><a href="#">Item III</a></li>
<li class="divider"></li>
<li><a href="#">Other</a></li>
</ul>
</div>

<div class="btn-group">
<a class="btn dropdown-toggle btn-select2" data-toggle="dropdown" href="#">Select a Region/City<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Item I</a></li>
<li><a href="#">Item II</a></li>
<li><a href="#">Item III</a></li>
<li class="divider"></li>
<li><a href="#">Other</a></li>
</ul>
</div>
<div class="btn-group">
<button type="submit" class="btn btn-primary">Search</button>
</div>

</div>
</form>
<!-- Search box End -->

Answer

You can set the selected dropdown text like this..

$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+'<span class="caret"></span>');
});

And then handle the search button click to get the selected values:

$("#btnSearch").click(function(){
    alert($('.btn-select').text()+", "+$('.btn-select2').text());
});

Working demo: http://www.bootply.com/63926