-1

I'm trying to add a click event on a bootstrap 5 dropdown items through javascript, jQuery to be more precise, however the event is not triggered on click, it is triggered once when the page loads without me clicking on it.

Here is an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
    <!-- JavaScript Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="btn-group" role="group" aria-label="Button group with nested dropdown">
    <button type="button" class="btn btn-primary">1</button>
    <button type="button" class="btn btn-primary">2</button>

    <div class="btn-group" role="group">
        <button id="btnGroupDrop1" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown
        </button>
        <ul class="dropdown-menu" aria-labelledby="btnGroupDrop1">
            <li><a class="dropdown-item" href="#">Dropdown link</a></li>
            <li><a class="dropdown-item" href="#">Dropdown link</a></li>
        </ul>
    </div>
</div>
<script>
    $('.dropdown-menu li a').on('click', console.log("TEST"))
</script>
</body>
</html>

One odd thing I noticed was that if I add an onclick attribute on one of the items then it behaves properly for that specific element:

<li><a onclick="console.log('TEST')" class="dropdown-item" href="#">Dropdown link</a></li>

The bootstrap example that I used for this can be found here https://getbootstrap.com/docs/5.0/components/button-group/#nesting

I want to add the click event through Javascript instead of using the onclick attribute, what am I doing wrong and what would be a possible solution?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

Update your <script>, like this.

<script>
  $(document).ready(function(){
    $('.dropdown-menu li a').on('click', function(){
      console.log("TEST");
    });  
  })
</script>

screenshot with output and changes enter image description here

Suneel Kumar
  • 756
  • 2
  • 5
  • 11