nixjojo
nixjojo

Reputation: 617

asp.net: Use javascript set lable value but it doesn't save

This is my code:

<form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    <input type="button" onclick="ontextchange();" />

    <asp:Button ID="Button1" runat="server"
        Text="Button" onclick="Button1_Click" />
</div>


function ontextchange() {

         document.getElementById("Label1").innerText="New";

    }

The problem is: I can change the lable value via javascript, but when I click the Button1, the lable value become the first one "Label". How can I get the new value when I click the asp.net button?

Upvotes: 0

Views: 1706

Answers (1)

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23084

You may try to use a hidden field instead, but you need to keep them synchronized in your client-side script and your server-side event handler.

<asp:Hidden ID="Hidden1" runat="server" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

In JavaScript:

function ontextchange() {
  // Set the label for the visual result
  document.getElementById("Label1").innerText="New";
  // Set the hidden input for the server
  document.getElementById("Hidden1").value="New";
}

Server-side you can read the hidden input and update the label (again, keeping them synchronized):

protected void Button1_Click(object sender, EventArgs e)
{
  // Set the label text to the value from the hidden input
  string value = Hidden1.Value;
  Label1.Text = value;
}

Upvotes: 3

Related Questions