Please navigate to the bottom of the page for Table of Contents

Saturday, July 16, 2011

jQuery to block paste in a textbox

In this min-post (and in the coming few posts), we will look at some quick ASP.NET and jQuery questions. These are real world, day-to-day problems that developers encounter and thus become very common interview questions.

Question: Consider an ASP.NET form which requires user to enter his name as confirmation (think Priceline’s site where you have to enter your initials as acceptance) in a textbox. We want to enforce the user typing into this textbox and not paste from somewhere else. How can you accomplish this using jQuery.

The key to solving this question is understanding the fact that jQuery allows you to bind to the “paste” event. The code do accomplish this is shown below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BlockPaste.aspx.cs" 
Inherits="jQueryInterviewQuestions.BlockPaste" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Block Paste</title>
<!-- include jQuery -->
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
   1:  
   2:     <script type="text/javascript">
   3:         // hook to the document ready function
   4:         $(document).ready(function () {
   5:             
   6:             // bind the paste operation
   7:             $('#<%=tbAccept.ClientID%>').bind('paste',
   8:                 function (e) {
   9:                     // prevent the default operation
  10:                     e.preventDefault();
  11:                     // warn the user
  12:                     alert("Paste disabled in this textbox");
  13:                 });
  14:  
  15:             });
  16:     
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
Please enter your name:
<!-- the textbox you want to disable paste on -->
<asp:TextBox runat="server" ID="tbAccept">
</asp:TextBox>
</div>
</form>
</body>
</html>

In the document.ready() function, we bind to the textbox in question’s “paste” event and prevent the default (paste) action. Then we warn the user that this is not allowed.

We can capture the cut and copy events in a similar fashion.

No comments:

Post a Comment