I have a bootstrap form that I have added a dropdown list. When I click on the dropdown I see the list, but when I click on it doesn't show as selected it still shows "select Domain" all the time. I found this link
https://www.codeply.com/go/pTWA3jYWEv/bootstrap-bootstrap-dropdown-selected-value
I have modified it, but I am missing something cause it is not working for me.
<div >
<div >
<button type="button"
id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Domain
<span ></span>
</button>
<div aria-labelledby="dropdownMenuButton">
<a >Corp</a>
<a >Domain2</a>
<a >Domain3</a>
<a >Local</a>
</div>
</div>
</div>
<script type="text/javascript">
$(".dropdown-menu li a").click(function(){
var selText = $(this).text();
$(this).parents('.dropdown').find('.btn btn-primary btn-user btn-block dropdown-toggle').html(selText ' <span ></span>');
});
</script>
CodePudding user response:
In order for Bootstrap dropdown to work, add the following CDN references in the HTML document to the project. Additionally select ".dropdown-menu a"
to capture the clicked <a>
element. The solution below provides an easy way to change the text of the <button>
element whose id is dropdown-button
when the dropdown button is clicked.
$(".dropdown-menu a").click( function() {
console.clear();
console.log($(this).text());
var selText = $(this).text();
$('#dropdown-button').html(`${selText} <span ></span>`)
});
.caret {
display: inline-block;
width: 13px;
height: 13px;
background-color: lightgray;
}
<!-- Add the following CDN references to the project. -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<div >
<div >
<!-- Added id attribute to this element. -->
<button id="dropdown-button" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Domain
<span ></span>
</button>
<div aria-labelledby="dropdownMenuButton">
<a >Corp</a>
<a >Domain2</a>
<a >Domain3</a>
<a >Local</a>
</div>
</div>
</div>