Retrieving the selected value from a Bootstrap dropdown using JavaScript when there are multiple dropdowns present

  • I have created multiple rows in javascript that are being rendered to the DOM from a Firestore collection.
  • Each row contains a Bootstrap dropdown with the same select options (".a" elements).
  • The id attribute of each row div is dynamically set based on the Firestore doc.id.
  • When a user clicks on the dropdown list, I want to retrieve the selected value from the dropdown of a specific row.

This is my implementation:

// Retrieve Firestore collection
db.collection('collection1').get().then(snapshot => {
snapshot.docs.forEach(doc => {

  // Create and render row...
  let row = document.createElement('div');
  let container = document.getElementById('myContainer');

  // Append row to the container element
  container.appendChild(row);

  // Set row id as doc.id for future reference
  row.setAttribute('id', doc.id);

  // Render Bootstrap dropdown here  
  document.getElementById(doc.id).innerHTML =
    '<span class="font-weight-bolder border rounded p-2 dropdown-toggle" id="selectStatus' +doc.id+ ' "  data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' + doc.data().status+ '</span>'
    +
    '<div class="dropdown-menu" aria-labelledby="selectStatus' + doc.id + '">' +
    '    <a class="dropdown-item" href="#">Action</a>' +
    '    <a class="dropdown-item" href="#">Another action</a>' +
    '    <a class="dropdown-item" href="#">Something else here</a>' +
    '  </div>';

   }); 
});

I've attempted this solution:

$('#someId a').on('click', function(){
$('#someOtherId').val($(this).html());
});

However, existing solutions I found seem to focus on a single dropdown element. In my scenario, there are multiple rows with individual dropdown elements where their ids vary per row.

I would appreciate any insights or guidance on solving this issue!

Answer №1

To better understand event handling, focus on the hyperlinks class rather than the IDs:

If you prefer using jQuery:

$('a.dropdown-item').on('click', function(e) { 
    // It's important to prevent default navigation behavior
    e.preventDefault();

    $('#someOtherId').val($(this).text());
});

Alternatively, with Vanilla JavaScript (ES6):

const elements = document.getElementsByClassName("dropdown-item");

const myHandler = (e) => {
    // Avoid navigating away from the current page
    e.preventDefault();

    const myElement = document.getElementById("someOtherId");
    
    myElement.value = this.text;
};

Array.from(elements).forEach(function(element) {
    element.addEventListener('click', myHandler);
});

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

"Encountering an error: invalid CSRF token in Node.js csurf

I have been utilizing the npm module csurf to generate a token. Initially, I retrieve the token from the server and then utilize it for the /register request. When I replicate these steps in Postman, everything seems to function correctly, but unfortunatel ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

What is the reason for the result of 0x80000000 & 0x80000000 being lower than 0?

What is the reason for this inconsistency in nodejs? 0x80000000 & 0x80000000 < 0 while 0x40000000 & 0x40000000 > 0 Also, if I were to use a larger hexadecimal number like 0x800000000, could it potentially introduce hidden bugs? POSTAG.t ...

The functionality of Jquery and JS lies in working on DOM elements as opposed to

Just to start off, I want to mention that my knowledge of JavaScript and specifically jQuery is quite limited. I've encountered an issue with some JavaScript and jQuery loading on my webpage. 1) I have written some code on JSFiddle http://jsfiddle.n ...

Converting text/plain form data to JSON using Node.js - step by step guide

I am currently working on a Node.js application to execute a POST call to an API for placing an order. However, the data I receive in our app is in text/plain format and not JSON. This is the current format of the data: TypeOrder=buy Coin=BTC AmountCoin= ...

Unable to invoke the Socket.on() function in NodeJS

I have set up a PHP web app and I am trying to integrate nodeJS into it. I followed a tutorial on nodeJS and got it working fine on localhost:3000. But now, I want to run it on a specific URL like localhost/final/chat/chat_index.html. To achieve this, here ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...

Rails 4 does not properly handle the execution of Ajax responses

Currently, I am incorporating ajax functionality within my Rails application. Within the JavaScript file of my application, the following code snippet is present: $('#request_name').on('focusout', function () { var clientName ...

The conversion from CSV to JSON using the parse function results in an inaccurate

I am having trouble converting a CSV file to JSON format. Even though I try to convert it, the resulting JSON is not valid. Here is an example of my CSV data: "timestamp","firstName","lastName","range","sName","location" "2019/03/08 12:53:47 pm GMT-4","H ...

Is it possible to restructure the address 51.xx.xx.xx:33xxx:user:pass to display as user:[email protected] :33xxx instead?

I am facing an issue with my current code where it only returns one proxy because it keeps rewriting over the existing ones. I want to avoid creating a new file and instead update the 'proxies.txt' file with each new proxy. const fs = require("f ...

Unveil SQL Limit with a Simple Scroll Load

After successfully laying out and creating my website, the next step is to load more results on scroll. This question has been posed numerous times before, but I am curious if there is a simple solution that can seamlessly integrate into my current setup. ...

Consistently receiving the identical result even when the checkbox remains unselected

Displaying a Checkbox Input <input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" /> The checkbox input will always have the value "AllValue ...

Steps for organizing a particular key in a map

I need assistance sorting my map based on the "time" value, but so far, I haven't been successful in finding a solution after searching online extensively. If anyone has any insights or recommendations, please share them with me. This is how my Map ...

The dictionary of parameters includes an empty value for the parameter 'imageWidth', which is of a non-nullable type 'System.Int32'

I am facing an issue with a function that executes an ajax call to an ActionResult. It sends a base64 string of an uploaded image along with some additional parameters containing information about the dimensions of the image. The data is sent to the server ...

Utilizing React to connect with Metamask and share the signer across various contracts

I'm currently working on a solution for sharing signers across multiple JavaScript files. In my walletConnect.js file, I successfully connect to Metamask and retrieve an ERC20 token contract. async function connect(){ try{ const accounts = awai ...

Overlooking errors in RxJs observables when using Node JS SSE and sharing a subscription

There is a service endpoint for SSE that shares a subscription if the consumer with the same key is already subscribed. If there is an active subscription, the data is polled from another client. The issue arises when the outer subscription fails to catch ...

I have a task to execute an Ajax request to retrieve and display data from my database table. My approach involves utilizing Perl CGI and attempting to invoke a Perl script using JavaScript

Encountering an issue in the web console with an error in the document.ready function showing an uncaught syntax error unidentified identifier. This CGI script contains JavaScript that calls a Perl script (TestAj.pl) which returns JSON data. I'm atte ...

Issue with the table not being displayed when any of the submitted fields are left empty

After submitting the first field, I receive the second value, and after submitting the second field, I get the third value. I have a group of three fields that are interconnected. <?php $courtname=''; if(!empty($_POST['court_ ...

Sending an Ajax POST request from a Node.js server

I am running a Node.js server with Socket.IO that communicates with a Python server using Django. I am looking to make a POST request from the Node.js server to the Django server on a specific method without utilizing any jQuery functions due to their depe ...