Suffii
Suffii

Reputation: 5784

How to Display Selected Item in Bootstrap Button Dropdown Title

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").

Upvotes: 196

Views: 453984

Answers (17)

ow3n
ow3n

Reputation: 6597

A simplified version using vanilla JS and Bootstrap 5.

let selectorBtn = document.querySelector('.dropdown-toggle');
let items = document.querySelectorAll('.dropdown-item');
items.forEach(item => {   
    item.addEventListener("click", function() {
        selectorBtn.innerHTML = item.text;
        selectorBtn.value = item.dataset.value;
        console.log(`innerHTML: ${selectorBtn.innerHTML}, value: ${selectorBtn.value}`);
    });
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>

<div class="btn-group m-1" role="group" aria-label="Type">
    <button type="button" class="btn btn-hornets dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
        Please Select From List
    </button>
    <ul class="dropdown-menu">
        <li><a class="dropdown-item" data-value="1" href="#">Item I</a></li>
        <li><a class="dropdown-item" data-value="2" href="#">Item II</a></li>
        <li><a class="dropdown-item" data-value="3" href="#">Item III</a></li>
        <li><a class="dropdown-item" data-value="4" href="#">Item IV</a></li>
    </ul>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

Upvotes: 0

Vincent Tallon
Vincent Tallon

Reputation: 376

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.

Upvotes: 1

Eklavya Chandra
Eklavya Chandra

Reputation: 108

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>

Upvotes: 0

Sully
Sully

Reputation: 14943

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());
    });

Upvotes: 10

Dmitrii Dubrovin
Dmitrii Dubrovin

Reputation: 631

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

Upvotes: 0

Nico Vink
Nico Vink

Reputation: 21

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>

Upvotes: 0

Mangirdas Skripka
Mangirdas Skripka

Reputation: 1647

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>');
        });
    });
});

Upvotes: 13

Sergio Promov
Sergio Promov

Reputation: 113

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());
   });
});

Upvotes: 4

cmcculloh
cmcculloh

Reputation: 48603

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

Upvotes: 156

WonderBoy
WonderBoy

Reputation: 145

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());
    });

Upvotes: 7

aGuegu
aGuegu

Reputation: 2299

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>');       
});

Upvotes: 1

Oskar
Oskar

Reputation: 2562

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>  

Upvotes: 7

ken
ken

Reputation: 14535

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>"
  );
});

Upvotes: 4

Jai
Jai

Reputation: 74738

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.

Upvotes: 178

Kyle Crossman
Kyle Crossman

Reputation: 694

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.

Upvotes: 28

NullPoiиteя
NullPoiиteя

Reputation: 57322

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

and in li add class="active"

Upvotes: 5

Murali Murugesan
Murali Murugesan

Reputation: 22619

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

Upvotes: 0

Related Questions