Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the onpaste function in javascript?

An input element on a web page is defined like the following to prevent passwords being pasted in:

<input type="password" class="field" id="password" name="password" title="Enter your password" maxlength="50" onpaste="javascript:return false;" size="38" tabindex="2">

I want to enable pasting in this input field. Using Firebug or equivalent I can edit the onpaste function so the code is:

onpaste="javascript:return true;"

This is fine for me, but for other users, I want a simpler solution. What came to mind is that if I could give them some Javascript, they could open the console and paste in a simple one-liner. However when I tried to do this the Javascript had no effect. I tried the following and neither worked.

$('#password').onpaste=""
$('#password').onpaste="javascript:return true;"

What am I doing wrong?

like image 336
Phil Avatar asked Jun 21 '26 05:06

Phil


2 Answers

The problem is that you're trying to combine jQuery with regular JavaScript. You can just use pure JavaScript to remove the onpaste listener.

document.getElementById('password').onpaste=""

If you want to use jQuery instead, you can use:

$('#password')[0].onpaste=""

which would give the same result.

like image 150
Anonymous Avatar answered Jun 22 '26 17:06

Anonymous


Just remove the onpaste attribute of the DOM element, not of the jQuery object which does not have a onpaste property. Your code is creating a property (set to a string) that is just being ignored.

In the example below, you can click the button and paste will be re-enabled.

document.querySelector('button').addEventListener('click', function() {
    document.getElementById('password').removeAttribute('onpaste');
})
<input type="password" class="field" id="password" name="password" title="Enter your password" maxlength="50" onpaste="javascript:return false;" size="38" tabindex="2">

<button>Allow pasting</button>
like image 39
Juan Mendes Avatar answered Jun 22 '26 19:06

Juan Mendes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!