-2

Working with latest Bootstrap 3.3.6 and jQuery library 1.11.3, I'm trying to have dropdown display the selected value when the user selects one of the options. So far it looks like the dropdown ul won't display at all.

HTML:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Select One
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu">
    <li><a href="#" data-value="a">A</a></li>
    <li><a href="#" data-value="b">B</a></li>
  </ul>
</div>

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

I referred to this thread for a working JS function but no avail: How to Display Selected Item in Bootstrap Button Dropdown Title

Current JSFiddle: https://jsfiddle.net/9xzqdry9/

Community
  • 1
  • 1
alu268
  • 63
  • 1
  • 2
  • 4

2 Answers2

6

You just need to reference your bootstrap.js AFTER your jquery.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'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Select One
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu">
    <li><a href="#" data-value="a">A</a></li>
    <li><a href="#" data-value="b">B</a></li>
  </ul>
</div>
Ricky
  • 22,575
  • 5
  • 39
  • 49
1

I saw your Current JSFiddle You should import first jQuery then Boostrap.js!

jmorc
  • 548
  • 3
  • 14
Julian Porras
  • 95
  • 1
  • 7