My colleague asked me how to disable the user input on a TextBox control. I won’t go into details about why this functionality was needed but here is a simple solution.



My colleague asked me how to disable the user input on a TextBox control. I won’t go into details about why this functionality was needed but here is a simple solution.

Whenever user inputs text into the textbox an onkeydown, onkeypress event is fired. I will be using the onkeydown event. The first solution is making the text empty or null when the onkeydown event is triggered. Here is the code for that:  

<asp:TextBox ID="txtName" onkeydown="clearInput(this)" runat="server"></asp:TextBox>

function clearInput(obj)
{
    obj.value = '';
}

Unfortunately, the discussed approach will not work and the first character will always be displayed in the textbox.

Another solution that comes to mind is to return false right after making the textbox empty.

function clearInput(obj)
{
    obj.value = '';
    return false;
}

This will also fail.

The solution to this problem is very simply which is to simply cancel the onkeydown event.

<asp:TextBox ID="txtName" onkeydown="return false" runat="server"></asp:TextBox>

You might say that you returned false from the clearInput method. Well, that was the return value of the function and had nothing to do with the event. If you do want to use your method then you need to use the return keyword as shown below:

<asp:TextBox ID="txtName" onkeydown="return clearInput(this);" runat="server"></asp:TextBox>

Hope it helps!