How to Display Selected Item in Bootstrap Button Dropdown Title
Asked Answered
S

17

196

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

Swanhildas answered 18/11, 2012 at 4:18 Comment(0)
G
178

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.

Gustative answered 18/11, 2012 at 4:45 Comment(12)
Hi Jai I tried ur sample link but it is not working there, besides I need to grab the selected value as well to post to database laterSwanhildas
@Behseini Can you please clarify "grab the selected value as well to post to database" which value?Gustative
i have updated the answer if current clicked item value you want to post in the db.Gustative
hi Jai sorry for late reply thanks for ur solution.the only problem I have is how I can put it in .ready() function? the solution works perfectly but when I merge it into document.ready() it stops working!Can you also let me know how did you end with the :first-child?! isn't' btn class a button ? so how we use the first child with it? I also will appreciate if you let me know how I capture the selected value in a variable to submit into database? Thanks again for your helpSwanhildas
Hi Behseini, this "$(function(){});" is equivilant to "$(document).ready(function() {});" you can find more information here:api.jquery.com/readyGustative
Hi Jai, thanks for solution.. this doesn't work for me when I have lists item <li> populated through ajax call. But, works fine for static <li> .. any ideas? I can ask another question with more details.Wendeline
@Gustative My related quetsion here #15979859Wendeline
This one is causing disappearing of down icon.Tamelatameless
@Teomanshipahi, that's because the code removes the inner span which is used to hold the down icon. This works (note that my code is in an event handler with event object e): $('.btn:first-child').html($(e.target).text()+' <span class="caret"></span>') I found this to be helpful: benknowscode.com/2013/12/…Kenward
Doesn't it seem a little hokey that THIS is the solution?Viewer
There's no dropdown in this example, though the question clearly states that it should implement a bootstrap dropdown.Adair
For Bootstrap 4 and above, its $(".dropdown-menu .dropdown-item").click(function ()Morganica
D
156

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

Disjunct answered 24/2, 2014 at 22:18 Comment(6)
Works great and I've just added them as below to hide the drop-down items after selection "$(this).parents(".btn-group").find('.selection').text($(this).text()).end() .children( '.dropdown-toggle' ).dropdown( 'toggle' );"Tegan
Update for Bootstrap 3.3.4: parents(".input-group-btn") needs to be replaced with parents(".dropdown")Analects
This should be the accepted answer after the change suggested by @Analects is added. Further, should you want to maintain the down caret on the button's text, you'll need to use .html instead of .text and concatenate the span onto $(this).text().Hobbs
@MattD, I wish I'd seen your comment before I commented on the accepted answer - you're spot on.Kenward
Worked like a charm for form submission after I added id="myselect" to the button properties.Homegrown
I suggest storing $(this).parents(".dropdown").find('.btn') in a variable instead of having jquery traverse the DOM twice.Odont
I
28

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.

Inapplicable answered 11/12, 2013 at 17:39 Comment(0)
G
13

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>');
        });
    });
});
Gigot answered 24/1, 2016 at 20:24 Comment(2)
Thanks ! this answer save me after waste my 10 minutes reading all other solutions.Tiana
This will preserve the caret so is a good solution!Frisk
C
10

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());
    });
Comet answered 23/2, 2019 at 13:8 Comment(1)
This answer also works when there are several dropdownsSavage
U
7

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>  
Urion answered 5/10, 2014 at 10:18 Comment(2)
How do you make the text on the dropdown change to what the user just selected? Say they selected option 1, then clicked off. The text for option one should be on the dropdown at this point, how do you do that?Deflective
When a user select an option " var selText = $(this).children("h4").html() " change the text.Urion
T
7

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());
    });
Threap answered 19/3, 2015 at 9:11 Comment(3)
I get "Uncaught ReferenceError: $xx is not defined" in strict modeThegn
Ivan did you find anything that works in strict mode?Tanberg
This works great for multiple bootstrap drop-down on the same page. Thank you!Fortna
Y
5

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

and in li add class="active"

Yet answered 18/11, 2012 at 4:31 Comment(0)
H
4

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>"
  );
});
Hodess answered 7/4, 2014 at 16:35 Comment(0)
S
4

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());
   });
});
Sleeper answered 7/11, 2015 at 20:58 Comment(0)
C
1

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>');       
});
Cuckoo answered 25/11, 2014 at 12:25 Comment(0)
P
1

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.

Prizefight answered 1/1, 2022 at 16:1 Comment(0)
P
0

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

Pendentive answered 18/11, 2012 at 4:25 Comment(2)
Hi Murali, Thanks for ur comment, I tried this but still not getting any thing var test = $('ul.dropdown-menu li').data('selected-item').find('a').text(); $("#nbtn").html(test); can you please let me know what I am doing wrong?Swanhildas
Please see the updated answer. I changed the code to $('ul.dropdown-menu li[data-selected-item] a').text(); Try thisPendentive
K
0

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

Kermes answered 17/3, 2016 at 11:55 Comment(0)
T
0

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>
Treblinka answered 4/3, 2018 at 19:19 Comment(0)
G
0

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>
Groupie answered 25/8, 2021 at 8:39 Comment(0)
M
0

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>
Michelson answered 7/3, 2023 at 17:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.