Bootstrap dropdown menu with Javascript List group

<div class="btn-group">
                <button type="button" class="btn btn-danger dropdown-toggle" 
                  data-toggle="dropdown" aria-haspopup="true" aria- 
                         expanded="false">
                    Sort <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <li><a href="#">By Name</a></li>
                    <li><a href="#">By Category</a></li>
                    <li><a href="#">By Price</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">Default Order</a></li>
                </ul>
            </div>


  <script type="text/javascript">

    $(function() {
        $(".dropdown-menu li a").click(function() {
            var selection = $(this).text();
           alert(selection);
        });

    });
</script>

I would like to display in an alert box the option I selected from the list. For instance, if I select "By Category," I want the alert to show "By Category" or any related information. Please assist me with this!

Answer №1

Update the code snippet from

var show = $('.dropdown-menu li a ').text();

Change it to

var show = $(this).text();. This modification will retrieve the currently selected item from the dropdown list.

$(function() {
  $(".dropdown-menu li a").click(function() {
    var show = $(this).text();
    alert(show);
  });
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="btn-group">
  <button type="button" class="btn btn-danger dropdown-toggle" 
    data-toggle="dropdown" aria-haspopup="true" aria- 
           expanded="false">
      Sort <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
      <li><a href="#">By Name</a></li>
      <li><a href="#">By Category</a></li>
      <li><a href="#">By Price</a></li>
      <li role="separator" class="divider"></li>
      <li><a href="#">Default</a></li>
  </ul>
</div>

Answer №2

Your code is looking good, but there is a slight issue with the event function where all the a elements are being selected instead of the one that is clicked. You can fix that by modifying the code to specifically target the clicked element like so:

$(".dropdown-menu li a").click(function(e) {
   var clickedItem = $(e.target).text();
   alert(clickedItem);
});

By adding the argument "e" to the event function, we can access the target element and use it as the selector for our code.

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

Having trouble accessing my API through localhost with NextJS

I'm currently working on an app that involves fetching data from my own API. The goal is to retrieve user-specific information and use it within the app. However, I've encountered a roadblock with CORS headers and I'm unsure of how to procee ...

Having trouble accessing the input class with jQuery

When I click the "Reset To Default Settings" button in my form, I want to clear the default colors in my 4 color pickers. Each of them has an input type text field with the class anyicon-form-colorpicker. To achieve this, I locate the <a> tag and use ...

Navigating horizontally within a list using Sencha Touch2

I currently have a list set up with the following configuration: var grid = Ext.create('Ext.List', { scrollable: { direction: 'horizontal', directionLock: true }, store: compStore, i ...

Query for string type data between specific dates in MongoDB

I have my data stored in this format on MongoDB: { "_id" : { "$oid" : "5385a437084ea4734b03374f" }, "linea" : 1, "egunak" : [ { "fetxa" : "2014/05/26", "turnoak" : [ { ...

A guide on using jQuery-Tabledit and Laravel to efficiently update table rows

In Laravel, it is necessary to include the row ID in the request URL to update it, for example: http://localhost/contacts/16 The challenge arises when using jQuery-Tabledit, which requires a fixed URL during initialization on page load. Hence, the query ...

The dynamically generated hyperlink is not displaying correctly

I've been attempting to display a link on my page, but instead of returning the /register path, it immediately redirects to the UTMs.... The href displayed on the site is domain.com/?utm_campaign... rather than domain.com/register?utm_campaign... ...

The functionality of jQuery's appendTo method seems to be malfunctioning

I am trying to display an image with a popup using jQuery mobile. In my loop, I have the code below: for( var i = 0; i < imageArray.length; i++ ) { counter ++; // Create a new Image element var img = $('<img data-rel="popup" class=" ...

Alternate the color over time using CSS

Is there a way to dynamically change the color of a div from black to white every two seconds, and then from white to black, continuously toggling as long as the div is visible? Essentially, I want the div to only be displayed when a user clicks and drag ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

The message from Vee-validate indicates that the validator 'required_if' does not exist within the system

I'm currently implementing vee-validate version 3 with Vue 2.7 in my project. Specifically, this is the entry in my package.json file for vee-validate: "vee-validate": "^3.4.5", My issue lies with getting the required_if rule to f ...

Using React and TypeScript to enable file uploads

Seeking assistance in creating a basic single select upload component. When I click a button that contains a hidden input field, the file dialog opens and allows me to choose a file. The placeholder then changes to display the selected file name along with ...

The HTML5 camera feature remains active even after navigating to a different page in an AngularJS application

I am currently exploring the video capabilities of HTML5. Using a directive userMedia, I have successfully activated my camera on my MacBook through navigator.getUserMedia() (using an adapter for cross-browser compatibility with supported browsers). Howev ...

Receiving JSON in a C# web service: A step-by-step guide

I created a JSON string using jQuery and now I want to send it to a C# web API controller. Here is an example of the JSON object: {"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} I attempted to send it with a URL structure like thi ...

Why is it that the reduce function is not returning the object I expected?

[['id', '1111'], ['name', 'aaaaa']] I came across this list. { id: '1111', name: 'aaaa' } Now, I would like to transform the list into a different format. My attempt to convert the list into t ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Tips for resetting form fields and clearing previous values before resubmitting the form, allowing for a fresh start with empty fields

Welcome to my website! If you visit , you'll notice a feature I've added that clears form field values after submission. However, I'm encountering an issue where the fields remain filled when revisiting the page for another appointment. I at ...

The connection between the layout of dropdown menus and the way data is handled in forms

I have discovered three different methods for creating dropdowns that can be used in forms: 1) Utilizing HTML with "form-dedicated" attributes such as select and option value="" 2) Implementing the Bootstrap framework with div classes like "dropdown", Butt ...

Discovering what is impeding the rendering of a webpage

On a particular website, the server rendering happens quickly but there seems to be a delay on the client side which is causing the HTML to be rendered few seconds later. I suspect it could be due to some setTimeout function or similar; are there any tool ...

Format specific words or characters in a text input

In HTML, when I want to display strings in a Text Input or TextArea, I am looking for a way to have specific substrings render with a box around them. I envision these boxed substrings as being treated as a single entity, similar to how highlighting or tex ...

When clicked, elevate the element to the top of the window with an offset

Is there a way to click on this button, which is located within an accordion section header, and have it automatically move to the top of the page based on the window size? It seems like it should be a simple task, but sometimes after a long day things ca ...