Obtain the chosen item from a Bootstrap4 dropdown menu by utilizing a button

I am struggling to get a button with dropdown working in Bootstrap4. Below is the HTML code:

<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>

Unfortunately, the JavaScript code just doesn't work as expected:

<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>

Answer №1

Here is some JavaScript code for you to try:

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

Check out this fiddle for a live example: https://jsfiddle.net/abc123xyz/

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

Display the HTML content once the work with AJAX and jQuery has been successfully finished

Below are the codes that I have created to illustrate my question. It's not a complete set of code, just enough to explain my query. The process goes like this: HTML loads -> calls ajax -> gets JSON response -> appends table row with the JSO ...

JavaScript: Employ array destructuring for improved code readability (eslintprefer-destructuring)

How can I resolve the ESLint error that says "Use array destructuring. eslint(prefer-destructuring)"? The error occurs on this line of my code: let foo = 1; foo = obj.data[i][1]; //ESLint error on this line If anyone could provide assistance in fixing thi ...

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

Divs animated with jQuery keep on moving even after the animation has finished

My current project involves animating a single circle that scales, collides with two nearby circles, and then causes those circles to animate to specific positions. While everything works as expected, there is an issue where the two circles involved in the ...

MS Edge modifies the attribute's empty value to 1

I have written a JavaScript code to extract values from a list, but in the Windows Edge browser, it returns a value of 1 even when the actual value of the <li> tag is blank. For example: HTML Code <ul> <li value="">Test 1</li&g ...

Even though I have successfully compiled on Heroku, I am still encountering the dreaded Application Error

Looking for help with a simple express/node application to test Heroku? Check out my app.js: const express = require('express') const app = express() const port = '8080' || process.env.PORT; app.get('/', function (req, res) ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...

Understanding the flattening process of arrays using JavaScript - Detailed explanation required

Currently, I am immersed in the captivating world of Eloquent JavaScript. However, I have hit a roadblock with one of the exercises that involves flattening a multi-dimensional array. Despite my best efforts, I have been unable to crack the code. After f ...

Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js fi ...

Utilize the request object from Express within a Mongoose Plugin

I have incorporated an API in ExpressJS along with a middleware that runs before each endpoint controller: app.use(segregationMiddleware); app.get('/some-endpoint', controller1); app.get('/some-endpoint-2', controller2); The segregat ...

Checkbox paired with a read-only text column

I have a simple HTML input field with JavaScript functionality, which includes a checkbox. I am trying to write text in the input field when the checkbox is checked, and make the input field read-only when it is not checked. Can anyone provide an example ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

Is it possible to use jQuery for drag-and-drop functionality?

Currently, I am working on developing a drag-and-drop widget that consists of 3 questions and corresponding answers. The user should only be able to fill in 2 answers in any order, while the third drop area should be disabled. This third drop area can be l ...

Multer failing to generate file during request process

My current setup involves a router and multer middleware, but I'm facing an issue where the file requested is not being created. As a result, req.file always remains undefined. const multer = require('multer'); let storage = multe ...

Issue with ThemeManager in Material UI & React: Constructor is not valid

Currently, I am integrating Material UI into a small React application, but I suspect that the tutorial I am following is outdated and relies on an older version of Material UI. The error _materialUi2.default.Styles.ThemeManager is not a constructor keeps ...

Distinguishing between selecting rows and selecting checkboxes in Mui Data Grid

Is there a way to differentiate between clicking on a row and clicking on the checkboxes? I want to be able to select multiple rows by clicking anywhere in the row except for the checkbox column. When clicking outside the checkbox column, I would like to p ...

Angular unburdened by jquery

I need help converting the following code from using JQuery to only Angular. I am unsure of how to accomplish this. Thank you! var startProduct = $("#product-overview").position().top - 60; var endProduct = $("#global-features").position().t ...

Issue with Ionic Framework Typescript: `this` variables cannot be accessed from callback functions

Is it possible for a callback function to access the variables within this? I am currently working with d3.request and ionic 3. I can successfully make a REST call using d3.request, but I am facing difficulty when trying to assign the response to my this. ...

How to Use AJAX to Read a Text File in JavaScript

Having trouble with AJAX! I have successfully set up a marquee on my website, but now I want it to dynamically fetch the text from a text file. The goal is to read the text from the file (which contains only one line) and assign it to a global variable nam ...

Using AngularJS to prefill a HTML5 date input field with a default value

Is there a way to bind the default value generated in moment to both the date and time input fields? I have tried using ng-model and directly binding it to the value attributes, but without success. Any suggestions on how to make this work? Edit: Addition ...