What might be stopping Javascript from saving the value to the clipboard?

On my ASP.Net website, I am incorporating basic Javascript functionality.

One particular task involves calculating a value and saving it in a hidden textbox, like this:

<asp:LinkButton ID="LinkButtonShare" runat="server" CssClass="btn btn-success" OnClientClick="copyToClipboard()"><i class="fa fa-share-square"></i> Share</asp:LinkButton>
<div class="hidden"><asp:TextBox ID="TextBoxCopyURL" runat="server" ClientIDMode="Static"></asp:TextBox></div>

Afterwards, the Javascript function below is executed.

function copyToClipboard() {
  var copyText = document.getElementById("TextBoxCopyURL");
  copyText.select();
  document.execCommand("copy");

  /* Alert with the copied text */
  alert("Copied the text: " + copyText.value);

Despite receiving an alert, the text string is not being copied to the clipboard in Firefox or Chrome, resulting in an issue illustrated in the image below:

https://i.sstatic.net/nzdoR.png

I am struggling to identify the issue with such a seemingly straightforward task.

Answer №1

I made a slight tweak to your code, but it essentially remains the same. It is functioning as intended. Visit this link to see it in action

function copyTextToClipboard() {
  var textToCopy = document.getElementById("inputfield");
  textToCopy.select();
  document.execCommand("copy");

  console.log(textToCopy.value); // logs the value that is copied
}

document.querySelector('#copyBtn').addEventListener('click', () => {
  copyTextToClipboard();
})

Keep in mind that accessing the clipboard content directly in JavaScript is not possible. You cannot trigger a paste event programmatically or view the clipboard content.

Answer №2

Looking at the sample provided here:

you can tackle this issue using the following method:

function copyToClipboard() {
    var copyText = document.getElementById("TextBoxCopyURL");
    copyTextValue = copyText.value;

    window.clipboardData.setData('Text' , copyTextValue );

    /* Alert displaying the copied text */
    alert("Copied text: " + copyTextValue );

}

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

Connecting buttons to JavaScript functions that interact with MySQL database entries

I am working on a task involving rendering a database table using XMLHttpRequest in JavaScript to a PHP page. My goal is to display each entry from the table as an HTML row/cell with two buttons within each "entry". These buttons should trigger specific Ja ...

Do ES6 features get transpiled into ES5 when utilized in TypeScript?

After implementing ES6 features such as template strings, arrow functions, and destructuring in a TypeScript file, I compile the code to regular JavaScript... Does the TypeScript compiler also compile the ES6 syntax, or do I need to utilize another compil ...

JS: Issue with iterating over objects

Within my JavaScript code, there exists an object named box_object with the following structure: ({ id:"3", text:"this is a box object", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", ...

Converting an Observable Array into a nested JSON structure

Having difficulty storing an array of information properly as JSON. A visual representation of the issue can be seen in this fiddle. Input a set of tags and check the console for output. Additional detail: An input captures a comma-separated list of tag ...

Troubleshooting problems with data rendering in jQuery

Currently, my goal is to use JQuery to display a menu of checkboxes based on a specific template in a div. To enhance user experience, I have included a search box that will filter the menu items. However, there is an unusual issue occurring. When the men ...

What is the reason for the immediate application of the set function in a useState hook within asynchronous functions?

While working with multiple set functions of a useState hook, I noticed different behaviors when calling them in sync and async functions. function Test() { console.log('app rendering starts.'); const [a, setA] = useState(1); const [b ...

Creating a singleton that injects a class with persistence throughout the duration of the request

My ASP.NET web application includes the following classes: public class AppContext : IAppContext { private readonly IDataContext _dataContext; public AppContext(IDataContext dataContext) { _dataContext = dataContext; } ... } pub ...

Running a script upon service initialization

Can code be run when a service is first initialized? For instance, if the product Service is being initialized, I'd like to execute the following code: this.var = this.sharedService.aVar; ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Can you explain the distinction between WebDriver and ChromeDriver?

I'm curious about the distinctions between ChromeDriver driver = new ChromeDriver(); and WebDriver driver = new ChromeDriver(); in Selenium 2 - Java. I've encountered both in tutorials and examples but I'm uncertain about how using eithe ...

Try implementing Underscore/Lodash to organize an object by values and convert it into an array of pairs that can be utilized with AngularJS ng

My goal is to showcase the details from the given object on the user interface using Angular's ng-repeat. It is essential for me to arrange the key/value pairs based on their values and exhibit them in sequential order in an array from highest to lowe ...

The position of the jQuery VirtualKeyboard is not displaying correctly

I'm currently experiencing an issue with the placement of the keyboard while using the Mottie/Keyboard plugin. The images provided below illustrate my desired outcome and the current behavior: https://i.sstatic.net/GULve.png Despite my attempts, the ...

What is the best way to retrieve a PDF file from another website and showcase it on our own site without any redirection?

Is there a way to display a pdf from another website without having to redirect to that site? I'm looking for a solution that involves using the URL directly. ...

Performing JavaScript functions after fetching an XSLT page via AJAX

Is there a way to trigger JavaScript at a particular time without relying on setInterval() or onClick()? The issue I'm facing is that when I click to load an XSLT page using Ajax, the JavaScript within it does not execute even though it's writt ...

Retrieve information from an XML document

I have some XML content that looks like this: <Artificial name="Artifical name"> <Machine> <MachineEnvironment uri="environment" /> </Machine> <Mobile>taken phone, test when r1 100m ...

What is the CoffeeScript alternative for () => { return test() }?

Currently, I am attempting to write this code in CoffeeScript and finding myself at a standstill... this.helpers({ events: () => { return Events.find({}); } }); ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...

Trouble with AJAX BitMovin: unable to process GET request

I've been struggling to find a solution to my problem as I cannot pinpoint what exactly to search for. My current issue involves using AJAX for a PHP Get request, causing it to submit and navigate away from the page. The BitMovin library appears to b ...

Slider for jQuery or Ajax framework

Currently, I am in search of a gauge that contains multiple concentric circles, with each circle displaying values of different entities, similar to the image provided. Each individual needle indicates the value of its corresponding entity. I have come a ...

Even though I am attempting to submit a form without refreshing the page using Ajax, it is still causing

I've searched high and low, read through numerous examples on various forums, and attempted to find the solution to my query but unfortunately, it still eludes me. Here's the particular scenario I'm facing: Main.php The main.php page featu ...