How to disable Paste (Ctrl+V) with jQuery? - javascript

How can I disable Paste (Ctrl+V) option using jQuery in one of my input text fields?

This now works for IE FF Chrome properly... I have not tested for other browsers though
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.

Edit: It's almost 6 years later, looking at this now I wouldn't recommend this solution. The accepted answer is definitely much better. Go with that!
This seems to work.
You can listen to keyboard events with jQuery and prevent the event from completing if its the key combo you are looking for.
Note, check 118 and 86 (V and v)
Working example here:
http://jsfiddle.net/dannylane/9pRsx/4/
$(document).ready(function(){
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
alert('thou. shalt. not. PASTE!');
event.preventDefault();
}
});
});
Update:
keypress doesn't fire in IE, use keydown instead.

As of JQuery 1.7 you might want to use the on method instead
$(function(){
$(document).on("cut copy paste","#txtInput",function(e) {
e.preventDefault();
});
});

jQuery('input.disablePaste').keydown(function(event) {
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
});

I tried this in my Angular project and it worked fine without jQuery.
<input type='text' ng-paste='preventPaste($event)'>
And in script part:
$scope.preventPaste = function(e){
e.preventDefault();
return false;
};
In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.

The following code will disable cut, copy and paste from full page.
$(document).ready(function () {
$('body').bind('cut copy paste', function (e) {
e.preventDefault();
});
});
The full tutorial and working demo can be found from here - Disable cut, copy and paste using jQuery

$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtInput" />

You can catch key event :
function checkEventObj ( _event_ ){
// --- IE explorer
if ( window.event )
return window.event;
// --- Netscape and other explorers
else
return _event_;
}
document.keydown = function(_event) {
var e = checkEventObject(_event);
if( e.ctrlKey && (e.keyCode == 86) )
window.clipboardData.clearData();
}
Not tested but, could help.
Source from comentcamarche and Zakaria

$(document).ready(function(){
$('#txtInput').live("cut copy paste",function(e) {
e.preventDefault();
});
});
On textbox live event cut, copy, paste event is prevented and it works well.

I have tested the issue on chrome browser and it is working for me.Below is a solution for preventing the paste code in your textbox and also prevent the right click.
$(".element-container").find('input[type="text"]').live("contextmenu paste", function (e) {
e.preventDefault();
});

$(document).ready(function(){
$('input').on("cut copy paste",function(e) {
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

Related

javascript not working on phone [duplicate]

I have created a simple code to handle keypress event:
var counter = 0;
$('input').on('keypress', function () {
$('div').text('key pressed ' + ++counter);
});
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+).
What could be the issue?
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup event:
// JavaScript:
var counter = 0;
document.querySelector('input').addEventListener('keyup', function () {
document.querySelector('div').textContent = `key up ${++counter}`;
});
// jQuery:
var counter = 0;
$('input').on('keyup', function () {
$('div').text('key up ' + ++counter);
});
Use jQuery's input event, like this:
$( 'input' ).on( 'input', function() {
...
} );
With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/
$(document).ready(function() {
var pattForZip = /[0-9]/;
$('#id').on('keypress input', function(event) {
if(event.type == "keypress") {
if(pattForZip.test(event.key)) {
return true;
}
return false;
}
if(event.type == 'input') {
var bufferValue = $(this).val().replace(/\D/g,'');
$(this).val(bufferValue);
}
})
})
Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.
Eg:
function getKeyCode(str) {
return str && str.charCodeAt(0);
}
function keyUp(){
var keyCode = getKeyCode("1");
}
I think it is bad idea to use other events in place of 'keypress'.
What you need to do is just include a jQuery file into your project.
A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.
You can download it from : https://jquerymobile.com/download/

JS onkeydown/onkeyup - convert to jQuery keydown/keyup

I currently have some js for phone number validation that is using inline event listeners in the input field. I need to change this example so that instead of attaching the event listeners inline, I would be targeting the DOM element in jQuery and adding the event listeners. Here's a working example of what I have so far: http://jsfiddle.net/yVdgL/21/
window.mask = function (e,f){
var len = f.value.length;
var key = whichKey(e);
if((key>=47 && key<=58) || (key>=96 && key<=105))
{
if( len==1 )f.value='('+f.value
else if(len==4 )f.value=f.value+')'
else if(len==8 )f.value=f.value+'-'
else f.value=f.value;
}
}
function whichKey(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
return code
}
and
<input type="text" name="phone" id="phone" onkeydown="mask(event,this)" onkeyup="mask(event,this)" maxlength="13" />
I tried this but was unable to achieve the functionality that I need.
i have update you jsfiddle example:-
jQuery(document).ready(function(){
jQuery('#edit-phone1').keyup(function(event){
mask(event,this);
});
jQuery('#edit-phone1').keydown(function(event){
mask(event,this);
});
});
click here to see working example:-
http://jsfiddle.net/yVdgL/38/
or you can try :-
$(document).ready(function() {
$('#edit-phone1').on("keyup keydown", function(e) {
mask(e, this);
});
});
link for this is:-http://jsfiddle.net/yVdgL/56/
In older, pre-HTML5 browsers, $("#phone").keyup( function ) or keydown is definitely what you're looking for.
In HTML5 there is a new event, "input", which behaves exactly like you seem to think "change" should have behaved - in that it fires as soon as a key is pressed to enter information into a form. $("#phone").bind('input',function);
You never defined event.
jQuery('#edit-phone1').keyup(function(){
jQuery('#edit-phone1').mask(event,this); //<-- what is event?
});
just add it
Second issue is you are treating window.mask like a jQuery plugin and it is not a plugin.
jQuery('#edit-phone1').keyup(function(event){ //<-- add event here
mask(event,this);
});

Alert when backspace is pressed inside textbox

I have a grid with three read-only columns. Whenever user goes in there and try to edit by pressing backspace, I need to alert by giving a message. I am using this script and it doesn't work? Can anyone correct me?
$(document).ready(function () {
$('#txtCode').bind('keypress', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}
});
instead of keypress try with keyup or keydown with .on() method:
$('#txtCode').on('keyup keydown', function (e) {
You can bind multiple events like this too.
and one more thing closing of $('#txtCode') seems to be missing });
$(document).ready(function () {
$('#txtCode').on('keyup keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); //<----");" this is the closing you misssed this
});
See the fiddle in action
If this is all the code you are testing, you weren't closing the function properly, annotated in my posted code. Also use keyup instead of keypress
$(document).ready(function () {
$('#txtCode').bind('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
}); /*<-- You weren't closing your function properly*/
});
Fiddle
You do indeed need to add a return false statement to ensure the character doesn't get deleted anyway. I also took it a step further and extended jQuery with a preventKeyUsage method.
$(document).ready(function () {
$.fn.preventKeyUsage = function (key, message) {
return this.each(function () {
$(this).on('keydown', function (e) {
return (e.keyCode === key) ? (function () {
alert(message);
return false;
})() : true;
});
});
};
$('#txtCode').preventKeyUsage(8, 'The column is read-only and is not editable');
});
New Fiddle
Working code is:
Java Script Code:
$(document).ready(function () {
$('#txtCode').bind('keypress keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
Here is the updated code
<input type="text" id="txtCode" />
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
return false;
}
});
});
Fiddle Demo
Try this
$(document).ready(function () {
$('#txtCode').on('keyup', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
DEMO (Working on Firefox & Chrome)
$('#textbox').keydown(function(event){
if(event.keyCode == 8){
alert("Backspace not allowed..");
return false;
}
});
http://jsfiddle.net/xF9jL/1/
You are missing }); of keypress. google chrome have issues with keypress, u can try keydown instead
$(document).ready(function () {
$('#txtCode').bind('keydown', function (e) {
if (e.which == 8) {
alert('The column is read-only and is not editable');
}
});
});
To use delete ,arrows, backspace keys in Chrome you must use keydown. keypress on these keys work only in Firefox and Opera.
DEMO
You can probably solve the underlying issue by either not using an element that accepts input, or by using the disabled attribute:
<textarea name="example" disabled>Some text</textarea>
If you are posting back to the sever, you should assume the user has edited the field, no matter what you do to prevent it.
keypress event won't give keycodes for all keys in all browsers . Better use keyup or keydown event which gives keycode for all keys in all browsers
In order to understand the difference between keydown and keypress, it is useful to understand the difference between a "character" and a "key". A "key" is a physical button on the computer's keyboard while a "character" is a symbol typed by pressing a button. In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

Bind enter key to specific button on page

<input type="button" id="save_post" class="button" value="Post" style="cursor:pointer;"/>
How can I bind the enter key on the persons keyboard to this specific button on the page? It's not in a form, and nor do I want it to be.
Thanks!
This will click the button regardless of where the "Enter" happens on the page:
$(document).keypress(function(e){
if (e.which == 13){
$("#save_post").click();
}
});
If you want to use pure javascript :
document.onkeydown = function (e) {
e = e || window.event;
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
break;
}
}
using jQuery :
$('body').on('keypress', 'input', function(args) {
if (args.keyCode == 13) {
$("#save_post").click();
return false;
}
});
Or to bind specific inputs to different buttons you can use selectors
$('body').on('keypress', '#MyInputId', function(args) {
if (args.keyCode == 13) {
$('#MyButtonId').click();
return false;
}
});
Vanilla JS version with listener:
window.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
alert('enter was pressed!');
}
});
Also don't forget to remove event listener, if this code is shared between the pages.
Maybe not quite what you're looking for but there is a HTML property that lets you assign a specific button called an access key to focus or trigger an element. It's like this:
<a href='https://www.google.com' accesskey='h'>
This can be done with most elements.
Here's the catch: it doesn't always work. for IE and chrome, you need to be holding alt as well. On firefox, you need to be holding alt and shift (and control if on mac). For safari, you need to be holding control and alt. On opera 15+ you need alt, before 12.1 you need shift and esc.
Source: W3Schools

How can I capture keyboard events are from which keys?

I googled and got the following codes on the Net.However, when I press a keyboard key,it is not displaying me an alert box. I want to get which character I have pressed in the alert box. How do I fix this?
<script type="text/javascript">
var charfield=document.getElementById("char")
charfield.onkeydown=function(e){
var e=window.event || e;
alert(e.keyCode);
}
</script>
</head>
<body id="char">
</body>
</html>
If you want to get the character typed, you must use the keypress event rather than the keydown event. Something like the following:
var charfield = document.getElementById("char");
charfield.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode > 0) {
alert("Typed character: " + String.fromCharCode(charCode));
}
};
try this jquery code
$("body").keypress(function(e){
alert(e.which);
});
I can't off the top of my head think of a good situation in which to use the "on some event" method of a DOM element to deal with events on that element.
The best practice is to use addEventListener (or attachEvent in older versions of Internet Explorer) like so:
charfield.addEventListener('keydown', function (e) { alert(e.keyCode); }, false);
If you want to account for attachEvent as well:
(function (useListen) {
if (useListen) {
charfield.addEventListener('keydown', alertKeyCode, false);
} else {
charfield.attachEvent('onkeydown', alertKeyCode);
}
})(charfield.addEventListener);
function alertKeyCode(e) {
alert(e.keyCode);
}
You'll get the appropriate key code:
charfield.onkeydown=function(evt){
var keyCode = (evt.which?evt.which:(evt.keyCode?evt.keyCode:0))
alert(keyCode);
}

Categories