What is the best way to apply a single function across various buttons in order to achieve consistent outcomes?

Is there a way to create an onclick function that works for multiple ids? I have tried using it with one id and it works, but when I try it with other ids, it doesn't work. I am looking for a solution that allows me to use the same onclick function with the same ids in all div elements.

I need someone to write a single Javascript function with a single id to achieve the same result for all three buttons.

Please review my code below;

function copy() {
  document.getElementById("label").innerHTML = document.getElementById("mySelect").value;
}
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
<!DOCTYPE html>
<html>

<head>
  <style>

  </style>
</head>

<body>

  <div class="dropdown">
    <p id="label">Mouse over me</p>
    <div class="dropdown-content">
      <select id="mySelect">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
      </select>

      <button onClick="copy();">Add</button>

    </div>
  </div>


  <div class="dropdown">
    <p id="label">Mouse over me</p>
    <div class="dropdown-content">
      <select id="mySelect">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
      </select>

      <button onClick="copy();">Add</button>

    </div>
  </div>

  <div class="dropdown">
    <p id="label">Mouse over me</p>
    <div class="dropdown-content">
      <select id="mySelect">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
      </select>

      <button onClick="copy();">Add</button>

    </div>
  </div>
</body>

</html>

Answer №1

To pinpoint the correct elements within the specific section, you can utilize .closest() like this:

<button onClick="copy(this);">Add</button>

and

function copy(el) {
  var dd = el.closest('.dropdown');
  dd.querySelector('p').innerHTML =  dd.querySelector('select').value;
}

var copy = function(el) {
  var dd = el.closest('.dropdown');
  dd.querySelector('p').innerHTML =  dd.querySelector('select').value;
}
<div class="dropdown">
    <p id="label">Hover over me</p>
    <div class="dropdown-content">
      <select id="mySelect">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
      </select>

      <button onClick="copy(this);">Add</button>

    </div>
  </div>

  <div class="dropdown">
    <p id="label">Hover over me</p>
    <div class="dropdown-content">
      <select id="mySelect">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
      </select>

      <button onClick="copy(this);">Add</button>

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

Execute the script before the Vue.js framework initiates the HTML rendering

In order to determine if the user is logged in or not, and redirect them to the login page if they are not, I am looking for a way to check the user's login status before the HTML (or template) loads. I have attempted to use beforeCreate() and variou ...

Issue encountered in React 18: The value on the left side of an assignment statement must be a variable or a property that can be accessed

After upgrading my React version from 17 to 18, I encountered an error with this code: data?.area?.width=['111','220']. The error message states "The left-hand side of an assignment expression must be a variable or a property access." W ...

Building a RESTful route architecture for three interconnected categories using Express and NodeJS

I am a beginner working on an API for an online store and I need help with determining the restful route structure. We are using Node, React, Express, and GraphQL. Can someone provide guidance on how to set this up? Here is our current setup: Our stor ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

Retrieving data from a nested object with varying key names through ng-repeat

My JSON object contains various properties with unique names: var definitions = { foo: { bar: {abc: '123'}, baz: 'def' }, qux: { broom: 'mop', earth: { tree: 'leaf', water: 'fi ...

Is there a way to retrieve two distinct data types from a single ng-model within a select option?

My mean stack code is functioning well, but I am looking to enhance it by adding a new feature. Specifically, I want to retrieve more elements from my NoSql database while selecting options. This is the structure of my database: Tir2 :id, price, xin, yin ...

The second AJAX request is unloading the outcome of the initial one

When the code below is executed in the onLoad event of the page, it first populates a drop down menu with getCompany() and then fills data from the server into text boxes while selecting the chosen option. Both functions work correctly when I reload the p ...

The issue with jqTransform not displaying the select box value on a hidden contact form

Could really use some assistance here and apologize if it's a hassle: Link to contact form To view the contact form, simply click the "Contact" button in the top left corner. The jqTransform jQuery plugin is being used to style it. Initially, it&apo ...

Combine and convert an array of objects

Implementing JavaScript functional programming techniques, how can the `status` field of `arr1` be aggregated/counted and then transformed into an array of key/value objects in `arr2`? arr1 = [ {'task':'do something 1', 'status& ...

A guide on applying a class to the parent element in VUEjs upon clicking the child menu

How can I dynamically add an active class to the <a> element of a sibling <router-link> when clicking on the sub menu in the provided template? <ul class="depth1"> <li class="m1"> <router-link to=" ...

Getting just the outer edges of intricate BufferGeometry in Three.js

Currently, I am immersed in a project that involves zone creation and collision detection using Three.js. The primary objective is for my application to effectively manage collisions and produce a BufferGeometry as the final output. My aim is to visually r ...

polygon with five or more sides

Can divs be created with shapes such as five or six corners? I am looking to create clickable zones on a map and any alternative methods would be greatly appreciated. ...

What could be causing the bootstrap columns to automatically shift onto separate lines?

Check out my code snippet: html, body { width: 100%; height: 100%; margin: 0; padding: 0; overflow-x: hidden; } .row { width: 100%; height: 80%; margin: 0px; padding: 0px; } body { background: #EFEFEF; } .container-fluid { wid ...

Immersive Visual Symphony through Dynamic Multi-Layered

My goal is to create captivating animations for my multiple background images. Here's the CSS code I've come up with: .header { background-image: url('/img/cloud2.png'), url('/img/cloud3.png'), url('/img/cloud1.png&apos ...

Bootstrap table with responsive design does not properly handle horizontal overflow

In my project, I attempted to customize a bootstrap table but encountered an issue when viewing the table on mobile devices. The 'table' always extends its width to fit 100% of the content within it. What I aim to achieve is for the table to have ...

Alert: The attempt to move_uploaded_file(sample_material/13-1.jpg) has failed due to the inability to open stream because the specified file or directory does not exist in C:xampp

After attempting to upload files to a directory, I encountered errors preventing successful upload as indicated at the end of this post. Interestingly, data submission to the database works flawlessly without file upload; the main issue lies in transferrin ...

Creating a query string in MongoDB using [Object] as a field

Currently, I am in the process of constructing a string within Meteor to delve deeper into my MongoDB data. The structure of my data can be seen here: Data In my JavaScript code for Meteor projects, I have formulated the string as shown below: const co ...

Leveraging AJAX for fetching files on the identical server

Just starting out with HTML and AJAX programming, so let's give it a shot: I've developed a website that populates a table with content from an external txt file (content.txt). The text file is hosted on a Windows 2003 webserver in the C:\I ...

The success callback function in jQuery.ajax() sometimes receives undefined parameters

In my current code, I am using an ajax call to communicate with a Wordpress file responsible for creating WP users. jQuery.ajax({ method: 'POST', dataType: 'json', url: ajax_object.ajax_url, // Post ...

Having issues with utilizing $fetchState in Nuxt 2.12

Recently, I've been exploring the new functionality outlined in the documentation. However, I'm encountering an error that states : Property or method "$fetchState" is not defined on the instance but referenced during render. Despite clearly ...