SYSK 118: ReadOnly or ContentEditable?

Consider this:  you want a text box on a web page to be not editable by the user, but you want to be able to change the text box’s contents in client side script and see the updated text on the server.

 

Did you know that if you set TextBox1.ReadOnly = true, the value set by the client side script will not be visible on the server?    Try it for yourself… Here is the code:

<form id="form1" runat="server">

    <div>

        <input id="Button2" type="button" value="Change Text via Client-Side Script" onclick="ChangeText();" />

    </div>

    <asp:TextBox ID="TextBox1" runat="server">initial text</asp:TextBox>

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="See Value on the Server-Side" />

</form>

<script language="javascript" type="text/javascript">

<!--

function ChangeText()

{

    form1["TextBox1"].setAttribute("innerText", "abc");

}

-->

</script>

 

 

public partial class MyForm : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        TextBox1.ReadOnly = true;

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

       Response.Write(TextBox1.Text + "<br>");

       

    }

}

However, if instead of setting TextBox1.ReadOnly property you set ContentEditable attribute to false, you’ll get the behavior you’re looking for:

TextBox1.Attributes["contentEditable"] = "false";

 

 

Special thanks to Vinay Kumar Baliyan who replied with the information used in this post to Les Cardinal‘s question.