Is there a way to duplicate various "Input fields" in JavaScript by clicking on different buttons or icons?

Project Description: I am working on a simple project that involves multiple input fields, each with its own unique "Copy icon" for copying text. However, I am facing an issue where only the first input field is being selected and copied when I click on the copy icon.

Problem: I need all copy icons to work individually so that clicking on each one copies the corresponding input field's content.

Desired Outcome: I want each copy icon to copy the text from its respective input field when clicked, allowing for seamless copying of different inputs.

Reference Design: Please refer to this image for a visual representation of the project

Answer №1

Take into consideration the following.

$(function() {
  $(".copyIcon").click(function() {
    var input = $(this).next();
    if (input.val() != "") {
      input.select();
      document.execCommand("copy");
    }
    input.blur();
  });
});
* {
  margin: 0px;
  padding: 0px;
  box-sizing: border-box;
}

body {
  width: 100%;
  background: #efefee;
  font-family: Arial, Helvetica, sans-serif;
}

.container {
  max-width: 700px;
  background: #fff;
  min-height: 100vh;
  margin: 0 auto;
}

header {
  width: 100%;
  padding: 1.25rem;
  background: #424242;
  color: #fff;
  font-family: Arim Madurai;
  text-align: center;
  text-transform: uppercase;
}

section {
  padding: 1rem 2rem;
}

section h2 {
  font-family: Arim Madurai;
  font-size: 1.25rem;
  color: #424242;
}

...

This method relies on the use of relative positioning for each icon and selects the adjacent next element.

Answer №2

It is crucial to understand that the id attribute should be unique as having the same id within the same document may lead to unintended consequences when selecting elements.

In my process, I first collected all the icons on the page and then accessed the input element by traversing through its parent, which can be useful if there is a need to modify the DOM structure.

Another important point to note is that using document.execCommand() is now deprecated, and it is recommended to utilize the more modern navigator.clipboard API.

const icons = [...document.querySelectorAll(".copyIcon")];

icons.forEach(icon => icon.addEventListener('click', _ => {
  icon.parentElement.querySelector('input').select();
  document.execCommand("copy");
}));

<div class="input-group">
  <label for="">Decimal</label>
  <ion-icon name="copy-outline" class="copyIcon"></ion-icon>
  <input type="text" placeholder="eg. 1324" id="copyText"> <!-- Remember to update the IDs for the inputs -->
</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

Attempting to store a specific h1 text.event as a variable, allowing it to be saved upon input of the initial letter

After typing the second key, you can continue to input more characters as desired. It is possible to customize the text displayed in the h1 using your own name or any other text of your preference without needing a textbox. $(document).keypress(functio ...

JavaScript 'await' throws error 'then is not defined'

Just starting out with async programming and I've noticed a common issue in similar threads - the problem of not returning anything. However, in my case, I am facing a different error message 'Cannot read property 'then' of undefined&ap ...

Ensure that newly added elements are aligned with the settings of the slide's

I've encountered an issue with my jQuery slider that affects a div's CSS on slide. Everything works as expected, except when I add a new div, the settings from the slider aren't applied to the new div until the slider is moved again. HTML ...

What is the best way to retrieve the date and time using the Open Weather API for a specific city

Currently, I am in the process of developing a weather application using React and integrating the Open Weather API. Additionally, I have incorporated an external library for weather icons. The functionality allows users to input a city name and receive t ...

What is the process to unregister a service worker from Django login and admin pages?

I utilized Django to create an application and integrated the service worker into it. However, I encountered an issue when navigating to the login and admin pages as I needed to disable the service worker in those specific areas. Learn more about Service ...

How to make an AJAX request in jQuery / JavaScript after a specific time interval has passed

Here is the code snippet I'm working with: $('input.myinput').each(function(){ var id = $(this).val(); var myajax = function(){ $.ajax({ url: ajax_url, type: "GET", data: ({ code: id ...

Send JSON data through a JQuery Ajax call and show the resulting response afterwards

I'm having trouble getting this code to work properly. I am using jQuery to capture the value of a dropdown selection, sending it via AJAX in JSON format to a PHP file, and then appending the response to a div with an id of #orderSummary. However, I n ...

Is the CSS property text-transform: Capitalize effective on <option> tags, and if it is, which web browsers support this functionality

I have a <select> element where I want to capitalize the text in each <option> tag. Specifically, I want the options to display as Bar and Baz instead of bar and baz. <style> option { text-transform: Capitalize; } </style> &l ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...

Expanding content will not cause Flexbox to stretch

I am facing an issue with a container that includes a header tag and a div. The height of the div is set to 100vh, causing it to consume all available space. Within the div, there are two additional divs. Everything works as expected until I add more conte ...

Issue finding a route based on dates

Hey everyone, I'm working on a feature where I need to fetch tasks made by a user within a specific date range provided by the user. However, I am facing some issues with getting the date and routing it. Here is the URL format that I am trying to work ...

Transform a SQL query into JSON following a distinct structure

My issue: I have a Json format, but it is not the format I need. First, I will show you my code, and then I will explain the desired Json model. I am unsure whether I should make changes to my PHP code, JavaScript code, or database. It seems that the array ...

Is there a way for me to align this to the corner of the top left side?

Let's dive into an example for better understanding: Check out this jsFiddle link Here is the HTML code snippet: <div id="a">AAAAAAA</div> <div id="b">BBBBBBB</div> <div id="c">CCCCCCC</div> <div id="d">DDD ...

Dynamically adding a class to the initial set of elements in a React map function

In my current project, I have a specific requirement where I need to assign a class to the first n elements of an array. These first n elements are obtained from the parent component and their count increases gradually. One approach that I considered was ...

Adjust the sizes of the points according to the level of zoom

I've been working on creating a dynamic map in d3.js that displays US Science funding agencies as points, with their sizes scaling based on zoom level. I referred to this starter kit for guidance. While there are other solutions out there, they often ...

What is the best method for interacting with multiple links in Puppeteer?

As a beginner with puppeteer, I am diving into the world of web scraping by attempting to create a simple scraping task. My Plan of Action The plan is straightforward: Visit a page, Extract all <li> links under a <ul> tag, Click on each < ...

The onChange event was not able to be activated within the material-ui radioGroup component

Utilizing the RadioButton component to showcase different options of a question within a custom-built component: import FormControl from "@material-ui/core/FormControl"; import FormControlLabel from "@material-ui/core/FormControlLabel"; import Grid from " ...

Only a handful of pictures all aligned in a row

How can I style two images to be on the same line? <div> <img src=""/> <img src=""/> </div> While this code gives me images on the same line, there are spaces between them. Using inline display did not solve the issue. Any suggest ...

Designing a fixed bottom footer enclosed within a wrapper that expands from the top header to the bottom footer

I have created the basic structure of my webpage using HTML / CSS. However, I now realize that I need a sticky footer that remains at the bottom of the screen with a fixed position. Additionally, I want the main content area, known as the "wrapper," to str ...

`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue? Here is my product schema: mongoose = ...