Is there a way to automatically close the dropdown when a button is clicked?

A Bootstrap 5 dropdown menu is displayed below, consisting of labeled checkboxes and equipped with data-bs-auto-close="outside" attribute to auto-close the menu on outside click.

<div class="dropdown">
  <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu">
    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option1" name="filter">
      <label for="option1">Option 1</label>
    </div>

    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option2" name="filter">
      <label for="option2">Option 2</label>
    </div>

    <div class="btn-group px-1 mt-2 w-100">
      <button onclick="closeFilter()" type="button" class="apply btn btn-sm btn-success">Apply</button>
      <button onclick="closeFilter()" type="button" class="reset btn btn-sm btn-success">Reset</button>
    </div>
  </div>
</div>

The objective is to close the menu when either the "Apply" or "Reset" button is clicked. Here is the function intended for this purpose:

function closeFilter() {
  let dropDown = event.target.closest('.dropdown');
  let dropDownButton = dropDown.querySelector('.dropdown-toggle');
  dropDownButton.style.border = '1px solid red';
  dropDownButton.dropdown('toggle');
}
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="dropdown">
  <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu">
    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option1" name="filter">
      <label for="option1">Option 1</label>
    </div>

    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option2" name="filter">
      <label for="option2">Option 2</label>
    </div>

    <div class="btn-group px-1 mt-2 w-100">
      <button onclick="closeFilter()" type="button" class="apply btn btn-sm btn-success">Apply</button>
      <button onclick="closeFilter()" type="button" class="reset btn btn-sm btn-success">Reset</button>
    </div>
  </div>
</div>

However, the function results in an error message:

dropDownButton.dropdown is not a function

Where could the mistake possibly lie?

Answer №1

To access the specific dropdown instance, you can utilize the function

bootstrap.Dropdown.getInstance(element)
.

function closeFilter() {
  let dropDown = event.target.closest('.dropdown');
  let dropDownButton = dropDown.querySelector('.dropdown-toggle');
  dropDownButton.style.border = '1px solid red';

  bootstrap.Dropdown.getInstance(dropDownButton).toggle();
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c57505751425363160d100d">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfddd0d0cbcccbcddecfff8a918c918c">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="dropdown">
  <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu">
    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option1" name="filter">
      <label for="option1">Option 1</label>
    </div>

    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option2" name="filter">
      <label for="option2">Option 2</label>
    </div>

    <div class="btn-group px-1 mt-2 w-100">
      <button onclick="closeFilter()" type="button" class="apply btn btn-sm btn-success">Apply</button>
      <button onclick="closeFilter()" type="button" class="reset btn btn-sm btn-success">Reset</button>
    </div>
  </div>
</div>

Answer №2

To achieve this, you will need to explicitly declare the dropDownButton element as a Bootstrap dropdown component

and then you can utilize the toggle method on it

  const dropdown = new bootstrap.Dropdown(dropDownButton);
  dropdown.toggle();

function closeFilter() {
  let dropDown = event.target.closest('.dropdown');
  let dropDownButton = dropDown.querySelector('.dropdown-toggle');
  dropDownButton.style.border = '1px solid red';
  const dropdown = new bootstrap.Dropdown(dropDownButton);
  dropdown.toggle();
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bedcd1d1cacdcaccdfcefe8b908d908d">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b0bdbda6a1a6a0b3a292e7fce1fce1">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />

<div class="dropdown">
  <button type="button" class="btn btn-success dropdown-toggle" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu">
    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option1" name="filter">
      <label for="option1">Option 1</label>
    </div>

    <div class="px-1">
      <input class="form-check-input" type="checkbox" id="option2" name="filter">
      <label for="option2">Option 2</label>
    </div>

    <div class="btn-group px-1 mt-2 w-100">
      <button onclick="closeFilter()" type="button" class="apply btn btn-sm btn-success">Apply</button>
      <button onclick="closeFilter()" type="button" class="reset btn btn-sm btn-success">Reset</button>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently sending multiple ajax requests

Seeking help with my ajax knowledge. Currently, I have a function that is supposed to insert multiple items into an SQL database using a PHP page. However, it seems to only be inserting the last item entered. Here's the code snippet: function submitI ...

What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/An ...

Assign a class to a dynamically loaded element on a webpage

As I work on developing my website, I am facing an issue that I need help with. My header is stored in a separate HTML document and it looks like this: <div class="topnav" id="myTopnav"> <a href="Index.html" id=" ...

Can you provide me with a step-by-step guide on how to implement Stripe's Custom Payment feature

Currently in the process of creating a customized payment module for my django application and in need of some assistance. At the moment, I am using Stripe's Checkout for handling payments, but I find it restrictive as it doesn't allow for comple ...

Invoke the JavaScript function on the HTML button click event, sending the ASP parameter

Currently, I am working with node and passing a parameter in the following manner: res.render('page.ejs',{"product" : product }); The paramter 'product' is in JSON format. Within the 'page.ejs' file, I am attempting to call ...

Encountering an error when attempting to access undefined property while using a method as a callback

Exploring OOP and angular is new to me. I am currently trying to implement a reusable table with pagination that triggers an API request when the page changes (pagination within the table component). The issue arises when I attempt to access my method usi ...

The issue with Mongoose populate failing to populate

I'm facing an issue with populating my users' car inventory. Each car has a userId attached to it upon creation, but for some reason, the population process isn't working as expected, and no errors are being displayed. Let's take a loo ...

Guide on attaching event handlers to a standard button template using Vue JS

Just diving into Vue.js and I have a specific requirement. I need to attach events to a generic button template. I attempted to do so using the following approach. Vue.component('ac-btn', { props: [ 'clickevent' ] ...

Techniques for transferring form data from JavaScript to Java

Currently in my application, I have a signup form and I am facing an issue with storing the data in the backend. Since I am not well-versed in the backend development, I am struggling with this task. I'm using Netbeans 7.0 as my IDE and MySQL 5.6 for ...

In search of javascript implementations of the pubhubsubbub protocol that are open source

Can you list out some of the open-source Javascript implementations for the PubSubHubbub protocol, starting with the publishing side? ...

Trouble with Ruby on Rails jQuery interactions when using the tokenInput gem

Currently, I am developing a rails app and attempting to incorporate this gem for a text field https://github.com/exAspArk/rails-jquery-tokeninput Despite having the gem correctly installed and included in my _form.html.erb file, I keep encountering the ...

"The Node.js program is unable to access the contents of the browser.js file when loaded in

After spending an unreasonable amount of time trying to debug this issue, I am still unable to resolve it. Currently, I am following a udemy tutorial where the instructor implements the same code provided below. However, despite my efforts, the code is not ...

How to modify the background color in Material Ui's datepicker?

Is there a way to customize the background color of my Material UI datepicker modal? To change the colors, you can use the createMuiTheme function from "@material-ui/core": const materialTheme = createMuiTheme({ overrides: { MuiPickersToolbar: ...

Vue component using axios for conditional state toggling

My Vue method/function triggers a state change and toggles text on a button upon click. pauseTask: function() { this.isOpen = !this.isOpen; this.pauseButton.text = this.isOpen ? 'Pause' : 'Resume'; }, While it works flawle ...

Exploring z-indices in event bubbling

JSFiddle: https://jsfiddle.net/uLap7yeq/19/ Issue Let's examine a scenario where there are two elements, canvas and div, positioned in the same location using CSS. The div has a higher z-index compared to the canvas, but how can we make sure events ...

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...

Error: Attempting to access property of undefined variable

I have searched for similar titles related to my issue, but I still haven't found a solution. The error I am encountering when clicking on agent_dashboard on the side panel is as follows: txtDisplayName = <div style="border:1px solid #990000;paddi ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

AJAX response from open cart is returning null JSON data

Hey there, I'm having a problem with my ajax request. It seems like I keep receiving a null value for json. Let me show you the JavaScript code... <script> $(document).ready( function() { $('#donate-box-submit').on('click' ...

I'm curious about the process by which custom hooks retrieve data and the detailed pathway that custom hooks follow

//using Input HOOK I am curious to understand how this custom hook operates. import { useState } from "react"; export default initialValue => { const [value, setValue] = useState(initialValue); return { value, onChange: event =&g ...