How to change dropdown button text on click

#36
300
1 Answer
Question Image

I have a dropdown list, I want to change dropdown button text acording to my dropdown items on click dropdown items


Related to:
javascript
0
Answer
Answer 1 of 1
# 25

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>
     
0
0
0
Related Articles

If you still have a question about this, submit it in our Q&A community - Ask Question