views:

130

answers:

2

I have a multiline textbox that by default, is set to ReadOnly. I would like a button on the page to change the control to allow it to be edited. I would like this code to run on the client side because the page renders slowly and I'd like to avoid the post back.

The problem I'm having is the javascript code that I wrote to remove the readonly attribute appears to have no effect. I posted a stripped down example that illustrates the problem for your review.

<%@ Page Language="C#" %>

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

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title>Test</title>
    <script  type="text/javascript" language="javascript">
    function EnableEditing() {
    var e = document.getElementById("<%=TextBox1.ClientID%>");
        var result = e.removeAttribute("readonly");
        alert(result);

    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>     </div>
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True" TextMode="MultiLine">test</asp:TextBox>        
        <input id="Button1"  onclick="EnableEditing()" type="button" value="Remove RO" />

    </form>
</body>
</html>
+3  A: 

TextBox1 is the server side id,

try

var e = document.getElementById("<%=TextBox1.ClientID%>");

 var result = e.removeAttribute("readonly",0);

or if you dont want the caseinsensitive search

 var result = e.removeAttribute("readOnly");//note upercase Only
Pharabus
Checking the source, the textbox has an ID of TextBox1.However I made you change anyway for the sake of accuracy. It made no difference. You still can't edit the textbox.
Aheho
@Aheho pass the second param in 0 (i ammended my code) to tell it to do a case insensitive search, you should use the ClientId too, it assures you get the correct Id which will not always be the same, especially if the controls are nested in other controls
Pharabus
That works. Thanks!
Aheho
+1  A: 

Use var e = document.getElementById("<%=TextBox1.ClientID%>");

Also, if you want to read the modified text on postback, you can't set the readonly attribute on the server control. You have to set it on the client only, as in: TextBox1.Attributes("readOnly") = "readOnly";

adam0101
Thanks for the clarification. I realized that when the textbox changes were not there on postback.
Aheho