I'm interested in duplicating the content within a tag from a list

Step 1 retrieve id from button

Step 2 duplicate contents in td for the same id

Access the code on Codepen: https://codepen.io/terecal/pen/LoxmbP?editors=1010

    $(".copy_code").click(function(e){
        e.preventDefault();
        var id = this.id
        alert("id : ", id)
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td>code</td>
  <td colspan="122" id="my_code_122"> hello world </td>
  </tr>  
</table>
<button type="button" name="button" id="122" class="copy_code">copy</button>

Is it possible?

p.s

I implemented your technique.

The provided code is functioning correctly

`

    $(".copy_code").click(function(e){
        e.preventDefault();
        var id = $(this).attr('id')
        alert("id : " + id)

        var text = document.getElementById(id),
        textVal = text.innerText;
        textTd = $(`#my_code_${id}`).text()

        alert("copied code " + textTd) // textVal  code copy

        // I want to replicate this content as if copying with ctrl + c. Is that achievable? Appreciate your guidance.
    });

`

The issue is almost resolved.

I simply aim to copy the retrieved text as though pressing ctrl + C

Could you assist me with achieving this?

ps2

The current code snippet looks like this

   $(".copy_code").click(function(e){
        e.preventDefault();
        var id = $(this).attr('id')
        alert("id : " + id)

        var text = document.getElementById(id),
        textVal = text.innerText;
        textTd = $(`#my_code_${id}`).text()

        alert("copied code " + textTd) // textVal  code copy
        // I want to replicate this content as if pressing ctrl + c. Is there a way? Thank you if you let me know.

        var dummy = document.createElement('textarea');
        dummy.value = textTd;
      
        document.body.appendChild(dummy );
        dummy.select();
       
        document.execCommand('copy');
        document.body.removeChild(dummy);

        alert("copied code2 " + textTd)
    });

and the copying feature works fine

but after pasting with ctrl + v

the new line (br) does not function ^^;;

original:
from django.contrib import admin
from django.urls import path, include
from . import views

app_name= 'css_challenge'
urlpatterns = [

]

copy:
 from django.contrib import adminfrom django.urls import path, includefrom . import views

app_name= 'css_challenge'urlpatterns = [

] 

Is it possible to maintain line breaks upon copying??

Answer №1

Here's a suggestion that might work for you. First, make sure to use a + instead of a , in your alert message. Additionally, consider whether you actually need the copy functionality for pasting text elsewhere. From what I know, copying usually works best with inputs and textareas. I'm not certain if other elements support this API. Nonetheless, the code below should help extract the text content. While I haven't run a test on it yet, feel free to give it a try.

$(".copy_code").click(function(e){
        e.preventDefault();
        var id = this.id
        alert("id : "+ id)
  
        var text = document.getElementById(id),
            textVal = text.innerText;
  
        console.log(textVal);
    });

Answer №2

If you're looking to experiment, perhaps consider this approach:

$(".copy_code").click(function(e){
        e.preventDefault();
        var idValue = $(this).attr('id');
        alert(idValue)

        // var copiedText = document.getElementById("my_code");
        // copiedText.select();
        // document.execCommand("copy");
        // alert("Copied the text: " + copiedText.value);

    });

Answer №3

If you want to copy text using JavaScript, there is a solution available. However, the process can be a bit cumbersome as the text needs to be inside an HTML element.

To begin, create a placeholder text element:

var placeholder = document.createElement('textarea');

Assign your desired text to it:

placeholder.value = selectedText;

Insert the placeholder into the DOM:

document.body.appendChild(placeholder);

Select the text within the placeholder:

placeholder.select();

Finally, copy the selected text to the clipboard:

document.execCommand('copy');

Don't forget to remove the placeholder element from the DOM once you're done:

document.body.removeChild(placeholder);

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

Learn how to change the icon in Vuejs when the class 'active' is present

I have a bottom navigation bar with icons. How can I make it so that when the router-link has the class 'active', the icon associated with it also becomes active? By default, the first icon is active. <li> <router-link v-if="ac ...

Navigating through JSON arrays can be achieved by utilizing iteration techniques

I'm having trouble with a script and can't figure out how to make it display in the designated div. It may have something to do with how I'm handling the response. In Chrome devtools, the response looks like this: { "[\"record one& ...

Next.js struggled to load an external image containing an extension within the URL

I am currently dealing with products that have images sourced from various remote servers. I am now looking to incorporate next.js images into the mix. However, after making some updates to the code, images from one server are no longer displaying properly ...

extract data from a JSON-formatted object

While developing my asp.Net application using MVC 3, I encountered a situation in which I was working with a jQuery control. I received a JSON response that looked like this: { "text":"Books", "state":"open", "attributes":{ ...

Is there a way to incorporate a pixel stream within a React component?

Calling all developers experienced in customizing webpages with pixel streams - I need your help! After following Unreal's documentation on pixel streaming (), I successfully set up a pixel stream. I can modify the default stream page, but I'm s ...

Interested in learning how to implement automatic data refreshing in real-time using React?

Exploring React by creating a basic Spotify app for the first time. Currently, the "Now playing" feature is triggered by a button click to display the user's current play. How can I make this update in real-time without the need for a button? <but ...

Sending a variable to a function in JavaScript (winJs) from a different function

Greetings! Currently, I am developing a Windows 8 app using Java Script. function fetchFromLiveProvider(currentList, globalList,value) { feedburnerUrl = currentList.url, feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&outpu ...

What's the Deal with MeshLine and Line Thickness in Three.js in 2021?

I was looking to create a curved line in Three.js with a thickness greater than one. After some research, I found that using Three.MeshLine seemed to be the solution. However, I have come across several reports (and experienced it myself) stating that the ...

Ways to receive a POST request from an external server on a GraphQL Server

Currently, I am working on a project that utilizes GraphQL. As part of the project, I need to integrate a payment processor. When a user makes a successful payment, the payment processor sends a POST request to a webhook URL that should point to my server. ...

Tips for transitioning from an old link to a new link within an MVC framework

Is there a way to redirect an old link to a new link in MVC? In Google search results, my old URL was cached as www.abcd.com/product?id=64 however, my new URL is now www.abcd.com/product/sample How can I set up a redirect so that when a user clicks on th ...

Tips for customizing the GeoDjango GeoJSON Serializer to incorporate model attributes

Here is a unique spin on how to include properties in JSON serialization, stemming from the following inquiry: from django.core.serializers.base import Serializer as BaseSerializer from django.core.serializers.python import Serializer as PythonSerializer ...

A guide on eliminating repetitions from an array of objects by utilizing the spread operator

I am working with an object array that has a unique key called "id": var test = [ {id: 1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""}, {id: 2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""}, {id: ...

Ensure that the folder name contains specific characters

When working with AngularJS, I am developing a feature to create folders. One requirement is that if a folder name contains special characters like /, :, ?, "<", or |, an error message should be displayed stating "A folder name cannot contain any of the ...

How can custom form validations be implemented with Angular's `useExisting`?

When looking at Angular's documentation on incorporating custom validators into template-driven forms — There is a straightforward example provided for implementing custom validation rules for an input field: required minlength="4" value shoul ...

Incorporating Highcharts into an Angular project

My goal is to recreate the chart that can be found at this link: http://jsfiddle.net/pablojim/Hjdnw/ but within my angular application. The difference is that I am using version 1.2.28 instead of v1.0 as shown in the example above. I have duplicated my s ...

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

JWplayer encounters loading issues preventing player usage

I'm currently utilizing JWPlayer 6 within my Django website. My goal is to showcase multiple videos on the same webpage. However, as I am iterating over objects, I am unable to assign distinct class IDs to the Jwplayer tag. Consequently, when I attemp ...

What is the best way to implement caching for an autosuggest feature in a component

I am currently working on a UI autosuggest feature that triggers an AJAX request while the user is typing. For example, if the user types mel, the response may include suggestions for cities like Melbourne, East Melbourne, and North Melbourne. { suggest ...

Django Authentication Made Easy

Currently working on a django-rest/React project where I am looking to implement simple (hard-coded) login/password authentication for the index page. The goal is to restrict access to the page based on this basic authentication, without requiring it for t ...

The server is receiving empty values from the Ajax post

I'm attempting to extract an image file from a base64 string received from the client side. Here is the ajax post I'm using: $.ajax({type: "POST", url: "upload_post.php", data: postData, dataType: "text", success: function(result){ ale ...