0

I am new to Javascript and trying to write a program to prevent text from being copied into textfield. the following is my code

function dontpaste()
{
  alert("hello");
  return true;
}

<input type="text" name="name" id="name" onpaste="dontpaste()">

The method is getting called. But the text gets copied after alert. Even

document.getElementById('name').value="";

is not working. Even tried with

return false;

for the method, still the text gets copied.

What needs to be done so that the method is called but text is not copied?

James Z
  • 12,209
  • 10
  • 24
  • 44
user2779311
  • 1,688
  • 4
  • 23
  • 31
  • 1
    What are you actually trying to do? Similar to sites that disable right-clicking, behaviors like these only serve to annoy — they're trivial to disable by the user. – Etheryte Apr 02 '21 at 15:28
  • 1
    Does this answer your question? [Disable pasting text into HTML form](https://stackoverflow.com/questions/1226574/disable-pasting-text-into-html-form) see this answer : https://stackoverflow.com/a/8797443/9977151 you can pass `event` to `dontpaste` and then use `preventDefault` – ATP Apr 02 '21 at 15:36

1 Answers1

1

This won't pass the event parameter doing it like this

<input type="text" name="name" id="name" onpaste="dontpaste()">

Change it to

<input type="text" name="name" id="name">
document.getElementById("name").addEventListener("paste", dontpaste);

then use event.preventDefault(); inside dontpaste function to block the default paste functionality.

Working example where paste doesn't work.

function dontpaste(event)
{
  event.preventDefault();
}

document.getElementById("name").addEventListener("paste", dontpaste);
<input type="text" name="name" id="name">
John
  • 3,716
  • 2
  • 19
  • 21
  • 1
    *technically* you can still get at the event via `this.event.preventDefault()`. But that's a bit gross. –  Apr 02 '21 at 16:00