Thursday 21 November 2013

ReadOnly TextBox causes page back when enter backspace key

1 comment
As Mention in the title of this post, the browser behavior always think that user want to go back(to previous page) when back space key in entered. So for the read only text box, the edit mode for the text box is not enable hence the backspace key will cause page to go back to previous page.

The solution is to put the JavaScript at the Read Only Text Box to prevent page from go back to previous page.

The Script

 function preventBackspace(e) {
             var evt = e || window.event;
             if (evt) {
                 var keyCode = evt.charCode || evt.keyCode;
                 if (keyCode === 8) {
                     if (evt.preventDefault) {
                         evt.preventDefault();
                     } else {
                         evt.returnValue = false;
                         alert("This is a read only field");
                     }                 }
                 else {
                     evt.returnValue = false;
                     alert("This is a read only field");
                 }
             }
             else
             {
                     evt.returnValue = false;
                     alert("This is a read only field");
             }

         }


Example to call js function

<asp:TextBox ID="TextBox1" ReadOnly="true" onKeyDown= "preventBackspace();"
  runat="server">
</asp:TextBox>

so if user click on the readonly textbox and try tu enter backspace key, the alert message will show .



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

1 comment:

  1. I have a field that i dynamically set to readonly depending on certain condition. Now this message appears even when the field at that time is not readonly. How does one prevent that? Thanks

    Sipho

    ReplyDelete

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.