最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trying to get the Bootstrap dropdown button text to change to the item selected - Stack Overflow

programmeradmin1浏览0评论

I'm using bootstrap to style a dropdown button and I'd like to have the button text change to whatever item is selected from the dropdown. I'm guessing JavaScript is the best way to make this happen, but I'm not that familiar with it yet. Any help would be greatly appreciated.
Here is my html for the first dropdown button. Thanks

    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Genre
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
      <button class="dropdown-item" type="button">Adventure</button>
      <button class="dropdown-item" type="button">Sci-Fi</button>
      <button class="dropdown-item" type="button">Comedy</button>
    </div>

I'm using bootstrap to style a dropdown button and I'd like to have the button text change to whatever item is selected from the dropdown. I'm guessing JavaScript is the best way to make this happen, but I'm not that familiar with it yet. Any help would be greatly appreciated.
Here is my html for the first dropdown button. Thanks

    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Genre
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
      <button class="dropdown-item" type="button">Adventure</button>
      <button class="dropdown-item" type="button">Sci-Fi</button>
      <button class="dropdown-item" type="button">Comedy</button>
    </div>
Share Improve this question asked Aug 28, 2020 at 5:50 MasterShake20MasterShake20 1051 gold badge3 silver badges10 bronze badges 2
  • Drop down is more of a menu. Really sounds like you would want to use a select here. Just my 2 cents – hawkstrider Commented Aug 28, 2020 at 5:58
  • Yeah, I tried a couple of things that didn't work and didn't think about including them. I'll include my attempts next time I reach out for help. – MasterShake20 Commented Aug 28, 2020 at 19:56
Add a ment  | 

4 Answers 4

Reset to default 6

@finiteloop thanks for your help. Based on the direction you pointed me in I added an onclick event for each dropdown element and added the following function which does what I need:

<div class="dropdown mx-3">
    <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
      Genre
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenu1">
      <button class="dropdown-item" type="button" onclick="showGenre(this)">Adventure</button>
      <button class="dropdown-item" type="button" onclick="showGenre(this)">Sci-Fi</button>
      <button class="dropdown-item" type="button" onclick="showGenre(this)">Comedy</button>
    </div>
  </div>
function showGenre(item) {
  document.getElementById("dropdownMenu1").innerHTML = item.innerHTML;
}

@MasterShake20 you could do something like this and integrate it into your code:

<!DOCTYPE html>
<html>
<body>

<form>
  Select your favorite fruit:
  <select id="mySelect">
    <option value="apple">Apple</option>
    <option value="orange">Orange</option>
    <option value="pineapple">Pineapple</option>
    <option value="banana">Banana</option>
  </select>
</form>

<p>Click the button to change the selected fruit to banana.</p>

<button id="btnTxt" type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  
let buttonVal = document.getElementById("mySelect").value;
document.getElementById('btnTxt').innerHTML = buttonVal;
  
}
</script>

</body>
</html>

See how this works here: https://www.w3schools./code/tryit.asp?filename=GI7I2WCF1N82

This is not exactly what you are trying to do, but it could set you in the right direction and give you an idea of what needs to happen.

Also, if you are just starting out, W3 is a great resource, so check their JavaScript Tutorials out here: https://www.w3schools./js/default.asp :D

with jquery is easy:

<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Number
</button>
<ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">1</a></li>
    <li><a class="dropdown-item" href="#">2</a></li>
    <li><a class="dropdown-item" href="#">3</a></li>
</ul>
<script>
    $(".dropdown-toggle").next(".dropdown-menu").children().on("click",function(){
        $(this).closest(".dropdown-menu").prev(".dropdown-toggle").text($(this).text());
    });
</script>

if you have more ponents in your page and want this behavior for specifics ponents, add an property to correct select only its: (in this example, add property changeable="true")

<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" changeable="true">
    Number
</button>
<ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">1</a></li>
    <li><a class="dropdown-item" href="#">2</a></li>
    <li><a class="dropdown-item" href="#">3</a></li>
</ul>
<script>
    $(".dropdown-toggle[changeable=true]").next(".dropdown-menu").children().on("click",function(){
        $(this).closest(".dropdown-menu").prev(".dropdown-toggle").text($(this).text());
    });
</script>

$(".dropdown-toggle").next(".dropdown-menu").children().on("click", function() {
  $(this).closest(".dropdown-menu").prev(".dropdown-toggle").text($(this).text());
});
<script src="https://cdn.jsdelivr/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
    Number
</button>
<ul class="dropdown-menu">
    <li><a class="dropdown-item" href="#">1</a></li>
    <li><a class="dropdown-item" href="#">2</a></li>
    <li><a class="dropdown-item" href="#">3</a></li>
</ul>

For those using Django, I was trying to find a solution to help me provide a filter button for recipe categories. So I took @MasterShake20's reply and did something like this:

HTML

           <div class="dropdown">
          <button class="btn btn-light dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Cuisine: {{cuisine}}
          </button>
          <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <a class="dropdown-item" href="{% url 'recipes' %}">All</a>
            {% for cuisine in cuisines %}
            <a class="dropdown-item" href="{% url 'recipes' %}?cuisine={{cuisine}}" onclick="showCuisine(this)">{{cuisine}}</a>
            {% endfor %}
          </div>
      </div>

Javascript:

  <script>
      function showCuisine(item) {
        document.getElementById("dropdownMenuButton").innerHTML = item.innerHTML;
       
      }
    </script>

views.py

def get_recipe_catalog(request):

    cuisine = request.GET.get("cuisine")

    if cuisine == None:
        recipes = Recipe.objects.all().order_by("name")
        cuisine = "All"

    else:
        recipes = Recipe.objects.filter(cuisine=cuisine)

    cuisines_qs = Recipe.objects.order_by().values('cuisine').distinct()
    cuisines = []
    for each in cuisines_qs:
        if each['cuisine'] is not None:
            cuisines.append(each['cuisine'])

    context = {'cuisine': cuisine}

    return render(request, 'recipes.html', context)
发布评论

评论列表(0)

  1. 暂无评论