elena
elena

Reputation: 4178

Bootstrap4 dropdown with button - get the selected element

I have a button with dropdown in Bootstrap4. The HTML looks as following:

<div class="row" id="dropdown-box">
  <div class="col-lg-6">
    <div class="input-group">
      <div class="input-group-btn" id="button-group-id">
        <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Select
        </button>
        <div class="dropdown-menu">
          {% for skill in skills %}
            <a class="dropdown-item" href="#">{{skill.name}}</a>
          {% endfor %}
        </div>
      </div>
      <input type="text" class="form-control" aria-label="Text input with dropdown button">
    </div>
  </div>

Here's the Javascript, that has no effect :(

<script>
  $( document ).ready(function() {
      $("#button-group-id").on("show.bs.dropdown", function(event){
          var x = $(event.relatedTarget).text(); // Get the text of the element
          console.log(x);
      });

  });
</script>

Upvotes: 0

Views: 731

Answers (1)

Znaneswar
Znaneswar

Reputation: 3387

Try with this js

$( document ).ready(function() {
     $(".dropdown-menu a").click(function(){
     var selText = $(this).text();
     console.log(selText);
    });
});

fiddle : https://jsfiddle.net/5rpwvzsw/

Upvotes: 2

Related Questions