How to change dropdown button text when an item is clicked?

Asked 2 years ago 125 views 1 answer Modified 1 days ago
9

I have a Bootstrap dropdown menu, and I want the dropdown button text to change to match the selected item when a user clicks on any dropdown option.

How can I implement this functionality using JavaScript or jQuery?

shama-naaz
50 reputation

1 Answer

0

You have not mentioned the dropdown list code in your question based on which we will write a code, here we are presenting bootstrap supported dropdown list whose button text will change according to the selected tab.

Check by clicking on this dropdown button:

 

  • Include bootstrap's CSS and JS links in your project: Get Bootstrap
  • Include google's ajax library in head section:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  • Include bootstrap dropdown menu code where you want:
    <div class="dropdown">
        <button class="btn btn-primary dropdown-toggle my-toggle-button" type="button" data-bs-toggle="dropdown" aria-expanded="false">
            Home
        </button>
        <ul class="dropdown-menu" id="my-active-tab">
            <li><a class="dropdown-item" href="#">Home</a></li>
            <li><a class="dropdown-item" href="#">Services</a></li>
            <li><a class="dropdown-item" href="#">Contect</a></li>
            <li><a class="dropdown-item" href="#">About Us</a></li>
        </ul>
    </div>
     
    • Give a own class or id to toggle button
    • Give a own class or id to dropdown-menu
  • Add this JavaScript code and edit its class and id according to your code:
    <script>
        $("#active-tab li").on("click", function() {
            $('.my-toggle-button').text($(this).text());
        });
    </script>
     
imran-nadwi
answered 2 years ago
You can use Markdown to format your answer.
Last edited: 2 years ago
Preview: