Issue
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 class="form-group">
<div class="dropdown">
<button class="btn btn-primary btn-user btn-block dropdown-toggle" type="button"
id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Domain
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item">Corp</a>
<a class="dropdown-item">Domain2</a>
<a class="dropdown-item">Domain3</a>
<a class="dropdown-item">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 class="caret"></span>');
});
</script>
Solution
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 class="caret"></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/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<div class="form-group">
<div class="dropdown">
<!-- Added id attribute to this element. -->
<button id="dropdown-button" class="btn btn-primary btn-user btn-block dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select Domain
<span class="caret"></span>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item">Corp</a>
<a class="dropdown-item">Domain2</a>
<a class="dropdown-item">Domain3</a>
<a class="dropdown-item">Local</a>
</div>
</div>
</div>
Answered By - Sercan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.