0

I have a page with multiple dropdowns 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 want to change the button text to selected element value. I've found this thread: How to Display Selected Item in Bootstrap Button Dropdown Title, which explains how to retrieve the text/value of selected item and change the text of the button, but there's a problem when there's more drop down menus on the page, the below script changes labels for all buttons present on the page:

$(function(){    
    $(".dropdown-menu li a").click(function(){    
      $(".btn:first-child").text($(this).text());
      $(".btn:first-child").val($(this).text());
   });  
});

How to modify it so that it would only change the corresponding dropdown menu button? As a side question: is there really no simple way of having <select> like behavior with dropdown menus out of the box in bootstrap?

Community
  • 1
  • 1
Stugal
  • 850
  • 1
  • 8
  • 24

2 Answers2

3

You need to add specificity to your jQuery selector. Currently, you're selecting all elements with a .btn class that are the first child of their parent. What you want to do instead is get the current element's parent .btn-group then find the .btn:first-child inside of that. You can do that as follows:

$(function(){    
    $(".dropdown-menu li a").click(function(){    
        $(this).closest('.btn-group').find(".btn:first-child").text($(this).text());
        $(this).closest('.btn-group').find(".btn:first-child").val($(this).text());
    });  
});
Danny Bullis
  • 3,043
  • 2
  • 29
  • 35
1

One of many potential solutions, transverse up the DOM to find the group it's in, and then target the button within the group.

$(function(){    
    $(".dropdown-menu li a").click(function(){ 
      var target = $(this).closest('.btn-group').find('.btn:first-child')
      target.text($(this).text());
      target.val($(this).text());
   });  
});
Dylan Watt
  • 3,357
  • 12
  • 16