Instructions on creating a non-editable text area where only copying and pasting is allowed

I am looking to simply copy and paste content into a textarea without needing to make any edits within the field.

<form action="save.php" method="post">

  <h3>Text:</h3>


  <textarea name="text" rows="4" cols="50"></textarea>

  <br><br>

  <input type="submit" name="submit" value="submit">

</form>

Answer №1

To restrict key presses to only ctrl+c, ctrl+v, or ctrl+x, follow these steps:

Allowed keys:

ctrl+c, ctrl+v, ctrl+x, as well as the Copy and Paste buttons on RightClick.

Restricted keys:

Everything

$('textarea').on('keydown', function(e) {
  var ctrl = e.ctrlKey ? e.ctrlKey : ((e.keyCode === 17) ? true : false);
  if (e.keyCode === 86 && ctrl || e.keyCode === 67 && ctrl || e.keyCode === 88 && ctrl) {
    return true;
  } else {
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name="text" rows="4" cols="50">Some Text</textarea>

Answer №2

Prevent editing in a textarea by disabling the keydown event and enabling the mousedown event. This way, users can only copy and paste without being able to make edits.

$(".area").bind("mousedown", function(e) {
  console.log('hello')
});
$(".area").bind("keydown", function(e) {
  console.log('world');
  event.preventDefault();
});
.touch {
  pointer-events: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>Text:</h3>


<textarea name="text" rows="4" cols="50" class="area"></textarea>

<br><br>

<input type="submit" name="submit" value="submit">

Answer №3

To ensure that the keydown event is blocked on a textarea for all keyboard keypresses except for ctrl+c, ctrl+v, command+c, and command+v keys.

For Mac users, utilize event.metaKey to detect the command key.

Try copying text from the textarea using ctrl+c or pasting text inside it using ctrl+v

Stack Snippet

var textarea = document.getElementById("text");

textarea.addEventListener("keydown", function(event) {
  var key = event.key;
  var cmd_key = event.metaKey;
  var ctrl_key = event.ctrlKey;
  if ((cmd_key && key == "c") || (ctrl_key && key == "c")) {
    return true;
  } else if ((cmd_key && key == "v") || (ctrl_key && key == "v")) {
    return true;
  } else {
    event.preventDefault();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
  <h3>Text:</h3>
  <textarea id="text" name="text" rows="4" cols="50">Copy this text and paste</textarea>
  <br><br>
</form>

Answer №4

Building upon Abhishek Singh's demonstration; in ES6 utilizing arrow functions and jQuery, it can be expressed concisely like this:

$textarea = jQuery("<textarea>")
     .on("keypress", (e) => e.ctrlKey && e.key == "v")

(Similar scenario but using "c" to restrict anything other than copy)

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

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Applying binary information to an image

Let's say I have an <img/>. The img is initially set with src='http://somelocation/getmypic'. Later on, there might be a need to change the content of the image based on some ajax call that returns binary data. However, this decision c ...

Can you provide instructions on how to use the jquery ajax post method to upload data to a MYSQL database

While I am familiar with performing a regular PHP post method where you specify the $conn variable containing the IP address and login details for the database, I find myself uncertain about how to achieve the same using jQuery AJAX post method. $.post( ur ...

Stopping a Bootstrap Modal Closure When Validation Errors are Present

I'm dealing with a bootstrap model within a .NET MVC5 app. Although my client-side validation is functioning properly (using jquery unobtrusive in MVC), I have encountered an issue where the modal keeps closing even when there are errors present. How ...

Vue.js variable routes present an issue where the Favicon fails to appear

I've successfully set my favicon in the index.html file for my Vue webpack SPA. It displays properly when I visit the main site or any standard route, but it fails to show up when I navigate to a dynamic route (path: "/traduzione/:translation"). I&ap ...

What is the best way to extract multiple children from a shared tag using BeautifulSoup?

My current project involves using BeautifulSoup to scrape thesaurus.com for quick access to synonyms of specific words. However, I've run into an issue where the synonyms are listed with different ids and classes for each word. My workaround is to tar ...

"Integrating `react-textarea-code-editor` with Remix: A Step-by-Step Guide

Upon loading the root of my web app, I encountered an error. The react-textarea-code-editor component is accessed via a separate route. The same error persisted even after following the suggestions provided here: Adding react-textarea-code-editor to the ...

Using the @ symbol in jQuery within an MVC framework can be achieved by first ensuring that

I'm attempting to incorporate the @ symbol into a JavaScript if condition, but I keep receiving an error. if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) { alert('yes'); ...

arrange a collection within an array containing keys as strings

I am facing an issue with sorting an array of objects. I need to sort the 'list' by 'score' in descending order. var list =[{ '440684023463804938': { score: 6, bonuscount: 2 }, '533932209300832266': { score: 20, b ...

What is the best way to initiate JavaScript using a button click in WordPress?

I need to add a button to a WordPress page that triggers a JavaScript function when clicked. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> < ...

Encountering an issue when attempting to send a post request with an image, resulting in the following error: "Request failed with status code

Whenever I submit a post request without including an image, everything goes smoothly. However, when I try to add an image, the process fails with an Error: Request failed with status code 409. Below is the code snippet for my react form page. const Entry ...

Ways to prevent users from pushing multiple child data or adding more than one child to a specific child in the Firebase database

How can we limit users from pushing more than one piece of data to the Firebase database in terms of security rules? I have attempted this approach without success. { "rules": { ".read": false, ".write": false, "voters": { // En ...

actions with frontend routing for CRUD operations

Imagine you are creating a simple CRUD todo application. Whether you choose to use Angular, React, or Vue for routing, the setup will be similar: /todos => see all todos /todos/:id => view one todo by id /todos/:id/edit => edit one todo by id /todos/new ...

Guide on accessing APIs for individual elements in an array

Currently utilizing Next.js / React.js and making use of this API to retrieve information about a specific country. Within the response, there exists an array called borders, as shown below: borders: [ "CAN", "MEX", ], There is ...

Dynamic Visibility Control of GridPanel Header in ExtJS

I have a GridPanel that needs to display a limited number of resources. If there are more resources available than what is currently shown, I would like the panel's header/title to indicate this by displaying text such as "more items available - displ ...

An issue has been identified where the 'connect' event in socket.io does not trigger on the client side

Looking to dive into the world of node.js and socket.io. I've put together a simple client-server test application, but unfortunately it's not functioning as expected. Running the system on a Windows machine with an Apache server setup. Apa ...

Tips for stopping a Node.js for loop if it runs for more than 20 seconds

Imagine a situation where I have a for loop performing some actions, and I want to terminate the loop if it takes longer than 20 seconds to complete. async function mainFunc(){ for (let step = 0; step < 5; step++) { // Executes a complex op ...

The encoding for double quotation marks vanishes when used in the form action

I am attempting to pass a URL in the following format: my_url = '"query"'; when a user clicks on a form. I have experimented with encodeURI and encodeURIComponent functions as well as using alerts to confirm that I receive either "query" or %2 ...

Exploring the Methods to Filter JSON Data in Node.js

There have been significant changes in technologies over the past couple of years since I last checked answers to this question. Currently, I am dealing with JSON files that are being transmitted from a database to my server. My main concern is how to eff ...

Tips for adding a scroll-to-top button on a page with only a vertical scroll bar

How can I make the scroll to top/bottom button only show up on pages with a vertical scrollbar? Currently, the button is not appearing when the page contains a vertical scrollbar. Any suggestions on how to implement this feature? ScrollToTopBottom.vue < ...