user5050407 user5050407 - 6 months ago 105
jQuery Question

jQuery/Bootstrap : dropdown-toggle is not setting the selected menu item as default selected item

I have a bootstrap dropdown but i am not able to set the selected menu item as default selected dropdown item?

<div class="dropdown">
<button class="btn dropdown-toggle" type="button" id="drpDownCat"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Select a Category<span class="caret"></span>
</button>

<ul class="dropdown-menu" aria-labelledby="drpDownCat">
<li><a class="dropdown-item" href="#">Category 1</a></li>
<li><a class="dropdown-item" href="#">Category 2</a></li>
<li><a class="dropdown-item" href="#">Category 3</a></li>
<li><a class="dropdown-item" href="#">Category 4</a></li>
</ul>
</div>

<script>
$('.dropdown-toggle').click(function()
{
$('.dropdown-menu').toggle();
});

</script>


I have created a JSFiddle for the above code.

Answer

Try this

$(function() {
  $(".dropdown-menu li a").click(function() {
    $(".btn:first-child").text($(this).text());
    $(".btn:first-child").val($(this).text());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/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 dropdown-toggle" type="button" id="drpDownCat" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Select a Category<span class="caret"></span>
  </button>

  <ul class="dropdown-menu" aria-labelledby="drpDownCat">
    <li><a class="dropdown-item" href="#">Category 1</a>
    </li>
    <li><a class="dropdown-item" href="#">Category 2</a>
    </li>
    <li><a class="dropdown-item" href="#">Category 3</a>
    </li>
    <li><a class="dropdown-item" href="#">Category 4</a>
    </li>
  </ul>
</div>

Comments