Wednesday, February 20, 2013

Prevent Cut, Copy and Paste Operations in a ASP.NET TextBox using jQuery


.aspx Markup:

<form id="form1" runat="server">
<div class="bigDiv">
<h2>Prevent Cut, Copy and Paste Operations in a TextBox</h2>
<asp:Label ID="lblEmail" runat="server"
Text="Re-Enter your Email Address"></asp:Label>
<asp:TextBox ID="tb1" runat="server"
Text="Try copying and pasting text here"
ToolTip="Try Copy/Cut/Paste in textbox"/>
<br />
Tip: Text can only be entered in this box. It cannot be
copied and pasted from a different textbox
</div>
</form> 
Jquery Script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('input[id$=tb1]').bind('cut copy paste', function(e) {
e.preventDefault();
alert('You cannot ' + e.type + ' text!');
});
});
</script>

The jQuery bind() function binds one or more events to a handler. Observe how convenient it is to list
multiple events (cut copy paste) together and bind it to a handler.
$('input[id$=tb1]').bind('cut copy paste', function(e) {}
If the user performs any of these events on the textbox, the default behavior is prevented using
e.preventDefault() and the user is alerted. The e.type describes the type of event performed.




1 comment:
Write comments
Recommended Posts × +