Disable backspace in textbox via javascript
Asked Answered
M

10

12

I have a textbox which is extended by an Ajax Control Toolkit calendar.

I want to make it so that the user cannot edit the textbox and will have to instead use the calendar extender for input.

I have managed to block all keys except backspace!

This is what I have so far:

<asp:TextBox ID="TextBox1" runat="server" onKeyPress="javascript: return false;" onKeyDown="javascript: return false;" onPaste="javascript: return false;" />

How would I also disable backspace within the textbox using javascript?

EDIT

Made an edit since I need a solution in javascript.

EDIT

It turns out that onKeyDown="javascript: return false;" DOES work. I have no idea why it wasn't working before. I tried using a new textbox and it blocked backspaces fine. So sorry to everyone who posted an answer hoping to get some rep esp. after I marked it for bounty.

My textboxes now (seem) to block ALL keystrokes and also still work with the calendar extender.

Miraculous answered 21/12, 2009 at 2:54 Comment(0)
H
39

ZX12R was close. This is the correct solution:

The TextBox is like this:

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

and the script looks like this:

<script type="text/javascript">
    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;
                }
            }
        }
    }
</script>

First of all, the backspace wont come through on Key Press, so you have to use Key Down.

Hawser answered 4/3, 2010 at 21:51 Comment(1)
very sensible and seems perfect..:) too bad Andrew found his own solution..;)Narcosynthesis
L
8

Can't you just use the HTML readonly="readonly" attribute?

<input type="text" name="country" value="Norway"   readonly="readonly" />

<textarea rows="3" cols="25" readonly="readonly">
It should work! :)
</textarea>
Lacasse answered 21/12, 2009 at 2:59 Comment(7)
Care to back that up with an ASP.NET equivalent?Office
TextBoxes should have the ReadOnly property: msdn.microsoft.com/en-us/library/…Lacasse
I believe it's ReadOnly="true". It doesn't allow readonly="readonly". I tried ReadOnly="true", but unfortunately, it doesn't play nicely with the calendar extender and validation.Miraculous
@Andreas Bonini - Koper: good find! However setting that property to true has a nasty side effect where the control's .Text property is unchanged on PostBacks, so the value set by the OPs calendar extender will be ignored. Stupid, but "by design" behavior. Perhaps a hack to get in the readonly HTML attribute is needed.Office
One thing to watch for with "ReadOnly" in ASP.NET: client-side changes will be ignored and overwritten with the value in viewstate. More here: dotnetslackers.com/ado_net/…Philistine
It's ReadOnly="true" on the server control, but as written in the answer (HTML) it's fine. We're using this with the CalendarExtender control, and while we have had some issues with the value on postback, we did get it to work eventually.Douglasdouglashome
If setting readonly on the server control makes problems, it's a far better solution to set in on the client so the control will work exactly the same on the server as if it wasn't set to readonly. And it will also take the load of the script engine in your browser, because you won't be executing much code. No event, no nothing. Just set something on document.onload.Caballero
S
4

How about using a label for the display and a hidden textbox to get the value back to the server?

Schoen answered 21/12, 2009 at 4:45 Comment(0)
L
2

You need to apply readonly on the client side controller ONLY, so that asp.net doesn't see it and still reads the data on postback. You can do this several ways, one of the easier if you use jQuery is to add a class to the text-boxes eg. cssclass="readonly" in question and $(".readonly").attr("readonly", true);.

Lowspirited answered 6/3, 2010 at 16:50 Comment(0)
S
1

As others said ReadOnly="True" will break the postback mechanism.

I believe you can get around it in your code-behind by accessing the Request object directly during PageLoad:

//assuming your textbox ID is 'txtDate'
if(Page.IsPostBack)
{
   this.txtDate.Text = Request[this.txtDate.UniqueID];
}

Your other option is to allow Disabled controls to postback on the form, but this is somewhat of a security concern as readonly fields modified via script could potentially come back:

<form id="MyForm" runat="server" SubmitDisabledControls="True">
..
</form>

http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.submitdisabledcontrols.aspx

I'm not sure the impact of this property on ReadOnly (vs Enabled="False") controls but it's worth trying.

And finally - I did run into the same issue you're having a few years ago, and from what I remember there is a difference between using an html input marked as readonly and runat="server", and an actual serverside control where ReadOnly="true".

I have a feeling doing:

<input type="text" readonly="readonly" runat="server" id="myTextBox" />

may have still allowed the data to come through, although in the code-behind you have to treat the control as a HtmlInputText or HtmlGenericControl vs. a TextBox. You can still access the properties you need though.

Just a few ideas anyway...

Stomy answered 22/12, 2009 at 21:16 Comment(0)
N
0

here is a possible solution... add an event listener...

<asp:TextBox ID="TextBox1" runat="server" onKeyPress="KeyCheck;" />

and then the function can be like this..

function KeyCheck(e) {
 var KeyID = (window.event) ? event.keyCode : e.keyCode;
 if (KeyID == 8 ) {
    alert('no backspaces!!);
 }
}

doubt if it has to be onkeypress or onkeyup...

Narcosynthesis answered 4/3, 2010 at 6:14 Comment(0)
C
0

ReadOnly attribute does not help. The backspace still is taking your browser to back page even if your text box is read only..

Chronister answered 8/3, 2010 at 12:42 Comment(0)
B
0

use regular text boxes not read-only and not Disabled, just use client-side JavaScript to ignore keypresses. This will ignore all keypress so you will have your READONLY behaviour and it will also ignore the backspace.

<input type="text" value="Your Text Here" onkeydown="return false;" />
Brittanybritte answered 3/4, 2011 at 15:53 Comment(0)
I
0

No Need to call any function and all just try this:

<asp:TextBox runat="server" ID="txt" onkeydown="return false;" 
    onpaste = "return false;" onkeypress="return false;" />
Impaste answered 1/3, 2012 at 18:59 Comment(0)
C
0

I was able to do something similar, with Jquery. Just putting it out here for reference!

$("#inputID").keypress(function (e)
{e.preventDefault();});

$("#inputID").keydown(function (e)
{e.preventDefault();});

the first prevents keypresses, while the second prevents key down events.

Still a JS noob, so feel free to point out good / bad things with this.

Condemnation answered 30/11, 2012 at 16:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.