Bootstrap Dropdown Button Change Text on Selection
Bootstrap provides a versatile framework for building responsive and visually appealing web applications. One common requirement is to dynamically change the text of a dropdown button based on the user's selection. In this tutorial, we'll explore a simple yet effective method to achieve this using JavaScript within a Bootstrap environment.
Thanks for your feedback!
Your contributions will help us to improve service.
How to Display Selected Item in Bootstrap Button Dropdown?
The HTML structure lays the foundation for our dropdown button. The button itself and the associated dropdown menu are defined within a container. The dropdown button initially displays the default text, "Select an option," and the dropdown menu contains a list of items with associated onclick events triggering the changeText
function.
In this example, the dropdown button is created using the button
element with the class btn btn-warning dropdown-toggle
. The list of items is created using the ul
element with the class dropdown-menu
. Each item in the list is created using the li
element with the class dropdown-item
. The onclick
attribute of each item calls the changeText
function with the selected item as the argument.
The changeText
function updates the text of the dropdown button with the selected item. It does this by setting the textContent
property of the button
element to the selected item.
That’s it! Now, when a user clicks on an item in the dropdown list, the text of the dropdown button will be updated with the selected item
JavaScript Code
Output of Above Example
The jQuery script in the code snippet targets all elements with the class “dropdown-item” and listens for a click event. When a user clicks on an item, the script retrieves the data-value attribute of the clicked item and updates the text of the dropdown button accordingly. This ensures that the text of the dropdown button is dynamically changed to the selected option whenever a dropdown item is clicked.