0

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?

1
  • 1
    You can't. when you click the button it posts the form to the server and the server provides a new HTML page. Labels don't get posted. You'd need to store the value in an input field if you want it posted to the server. Commented Jan 12, 2012 at 7:57

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.