How to Display Selected Item in Bootstrap Button Dropdown Title

JqueryTwitter Bootstrap

Jquery Problem Overview


I am using the bootstrap Dropdown component in my application like this:

<div class="btn-group">
    <button class="btn">Please Select From List</button>
    <button class="btn dropdown-toggle" data-toggle="dropdown">
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
       <li><a tabindex="-1" href="#">Item I</a></li>
       <li><a tabindex="-1" href="#">Item II</a></li>
       <li><a tabindex="-1" href="#">Item III</a></li>
       <li class="divider"></li>
       <li><a tabindex="-1" href="#">Other</a></li>
    </ul>
</div>

I would like to display the selected item as the btn label. In other words, replace "Please Select From List" with the list item that has been selected("Item I", "Item II", "Item III").

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Solution 3 - Jquery

I was able to slightly improve Jai's answer to work in the case of you having more than one button dropdown with a pretty good presentation that works with bootstrap 3:

Code for The Button

<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
	Option: <span class="selection">Option 1</span><span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
	<li><a href="#">Option 1</a></li>
	<li><a href="#">Option 2</a></li>
	<li><a href="#">Option 3</a></li>
  </ul>
</div>

JQuery Snippet

$(".dropdown-menu li a").click(function(){

  $(this).parents(".btn-group").find('.selection').text($(this).text());
  $(this).parents(".btn-group").find('.selection').val($(this).text());

});

I also added a 5px margin-right to the "selection" class.

Solution 4 - Jquery

This single jQuery function will do all you need.

$( document ).ready(function() {
    $('.dropdown').each(function (key, dropdown) {
        var $dropdown = $(dropdown);
        $dropdown.find('.dropdown-menu a').on('click', function () {
            $dropdown.find('button').text($(this).text()).append(' <span class="caret"></span>');
        });
    });
});

Solution 5 - Jquery

Another simple way (Bootstrap 4) to work with multiple dropdowns

    $('.dropdown-item').on('click',  function(){
		var btnObj = $(this).parent().siblings('button');
		$(btnObj).text($(this).text());
		$(btnObj).val($(this).text());
	});

Solution 6 - Jquery

Here is my version of this which I hope can save some of your time :)

enter image description here jQuery PART:

$(".dropdown-menu").on('click', 'li a', function(){
  var selText = $(this).children("h4").html();
  

 $(this).parent('li').siblings().removeClass('active');
    $('#vl').val($(this).attr('data-value'));
  $(this).parents('.btn-group').find('.selection').html(selText);
  $(this).parents('li').addClass("active");
});

HTML PART:

<div class="container">
  <div class="btn-group">
    <a class="btn btn-default dropdown-toggle btn-blog " data-toggle="dropdown" href="#" id="dropdownMenu1" style="width:200px;"><span class="selection pull-left">Select an option </span> 
      <span class="pull-right glyphiconglyphicon-chevron-down caret" style="float:right;margin-top:10px;"></span></a>
    
     <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
       <li><a href="#" class="" data-value=1><p> HER Can you write extra text or <b>HTLM</b></p> <h4> <span class="glyphicon glyphicon-plane"></span>  <span> Your Option 1</span> </h4></a>  </li>
       <li><a href="#" class="" data-value=2><p> HER Can you write extra text or <i>HTLM</i> or some long long long long long long long long long long text </p><h4> <span class="glyphicon glyphicon-briefcase"></span> <span>Your Option 2</span>  </h4></a>
      </li>
      <li class="divider"></li>
   <li><a href="#" class="" data-value=3><p> HER Can you write extra text or <b>HTLM</b> or some </p><h4> <span class="glyphicon glyphicon-heart text-danger"></span> <span>Your Option 3</span>  </h4></a>
      </li>
    </ul>
  </div>
  <input type="text" id="vl" />
</div>  

Solution 7 - Jquery

This one works on more than one dropdown in the same page. Furthermore, I added caret on selected item:

    $(".dropdown-menu").on('click', 'li a', function(){
        $(this).parent().parent().siblings(".btn:first-child").html($(this).text()+' <span class="caret"></span>');
        $(this).parent().parent().siblings(".btn:first-child").val($(this).text());
    });

Solution 8 - Jquery

you need to use add class open in <div class="btn-group open">

and in li add class="active"

Solution 9 - Jquery

Further modified based on answer from @Kyle as $.text() returns exact string, so the caret tag is printed literally, than as a markup, just in case someone would like to keep the caret intact in dropdown.

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

Solution 10 - Jquery

I have corrected script for multiple dropdowns on the page

$(function(){
    $(".dropdown-menu li a").click(function(){
    	var item = $(this);
    	var id = item.parent().parent().attr("aria-labelledby");

      	$("#"+id+":first-child").text($(this).text());
      	$("#"+id+":first-child").val($(this).text());
   });
});

Solution 11 - Jquery

It seems to be a long issue. All we want is just implement a select tag in the input group. But the bootstrap would not do it: https://github.com/twbs/bootstrap/issues/10486

the trick is just adding "btn-group" class to the parent div

html:

<div class="input-group">
  <div class="input-group-btn btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
      Product Name <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" role="menu">
        <li><a href="#">A</a></li>
        <li><a href="#">B</a></li>
    </ul>
  </div>
  <input type="text" class="form-control">
  <span class="input-group-btn">
    <button class="btn btn-primary" type="button">Search</button>
  </span>
</div>

js:

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

Solution 12 - Jquery

Once you click the item add some data attribute like data-selected-item='true' and get it again.

Try adding data-selected-item='true' for li element that you clicked, then

   $('ul.dropdown-menu li[data-selected-item] a').text();

Before adding this attribute you simply remove existing data-selected-item in the list. Hope this would help you

For information about data attribute usage in jQuery, refer jQuery data

Solution 13 - Jquery

For example:

HTML:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
     <BtnCaption>Select item</BtnCaption>
     <span class="caret"></span>   
  </button>
  <ul class="dropdown-menu">
     <li><a href="#">Option 1</a></li>
     <li><a href="#">Option 2</a></li>
     <li class="disabled"><a href="#">Option 3</a></li>   
  </ul> 
</div>

I use new element BtnCaption for changing only button's text.

Paste into $(document).ready(function () {} the following text

JavaScript:

    $(".dropdown-menu li:not(.disabled) a").click(function () {
        $(this).closest(".dropdown").find(".btn BtnCaption").text($(this).text()));
    });

:not(.disabled) don't allow use the disabled menu items

Solution 14 - Jquery

I had to put some the displayed javascripts above inside the "document.ready" code. Otherwise they didn't work. Probably obvious for many, but not for me. So if you're testing look at that option.

<script type="text/javascript">
$(document).ready(function(){
//rest of the javascript code here
});
</script>

Solution 15 - Jquery

I prefer using a selective floating label for that

<div class="form-floating">
<select class="form-select" id="floatingSelect" aria-label="Floating label select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<label for="floatingSelect">Works with selects</label>
</div>

Solution 16 - Jquery

Quite an old question but... I wanted to do it in plain/vanilla JS, so, here is my answer for doing it this way (ECMAScript 2015 (ES6) syntax, working on Bootstrap 5.1) :

let selectorList = Array
    .from(document.querySelectorAll('dropdown-menu'))
    .forEach(selector => {
        //Add an event listener for displaying the selected dropdown item
        selector.addEventListener("click", function() {
           let selectorButton = selector.previousElementSibling || selector.nextElementSibling;
           selectorButton.textContent = this.querySelector(":checked").value;
           selectorButton.value = this.querySelector(':checked').value;
        });
    });

I'm using the JQuery siblings() idea by using the JS previousElementSibling() || nextElementSibling() methods, which will find the button element right before or after the <ul class="dropdown-menu"></ul> element.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuffiiView Question on Stackoverflow
Solution 1 - JqueryJaiView Answer on Stackoverflow
Solution 2 - JquerycmccullohView Answer on Stackoverflow
Solution 3 - JqueryKyle CrossmanView Answer on Stackoverflow
Solution 4 - JqueryMangirdas SkripkaView Answer on Stackoverflow
Solution 5 - JquerySullyView Answer on Stackoverflow
Solution 6 - JqueryOskarView Answer on Stackoverflow
Solution 7 - JqueryWonderBoyView Answer on Stackoverflow
Solution 8 - JqueryNullPoiиteяView Answer on Stackoverflow
Solution 9 - JquerykenView Answer on Stackoverflow
Solution 10 - JquerySergio PromovView Answer on Stackoverflow
Solution 11 - JqueryaGueguView Answer on Stackoverflow
Solution 12 - JqueryMurali MurugesanView Answer on Stackoverflow
Solution 13 - JqueryDmitrii DubrovinView Answer on Stackoverflow
Solution 14 - JqueryNico VinkView Answer on Stackoverflow
Solution 15 - JqueryEklavya ChandraView Answer on Stackoverflow
Solution 16 - JqueryVincent TallonView Answer on Stackoverflow