ScottieB
ScottieB

Reputation: 4052

Change asp:label with jQuery then access in codebehind

I know, crazy right.

So I have an asp label and I want to fill it with jQuery. Later, in the codebehind I want to access this text for something else.

What I have is:

<asp:Label ID="myLabel" runat="server" />
<asp:Button ID="clickMe" runat="server" Text="Click!" OnClientClick="runMe();" 
   OnClick="clickMe_Click()" />

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

   function runMe () {
      $("#<%=myLabel.ClientID").text("here");}
</script>

protected void clickMe_Click(object sender, EventArgs e)
{
   string isIt = myLabel.Text;
}

So if I put a breakpoint on whatever code follows 'isIt' definition and look at it, isIt="". Is there a way to make this work? I'm guessing since jQuery's acting on the html it is actually altering the not the actual ASP.NET label.

Upvotes: 2

Views: 4358

Answers (3)

Jamshaid K.
Jamshaid K.

Reputation: 4547

An asp:Label element in the browser is rendered as a span element. So, setting the value would not work on it. We should either set the inner Text or inner Html of the asp:label or span element if working with Jquery/javascript. Like below:

$("#<%= myLabel.ClientID %>").text("MY UPDATED TEXT");
$("#<%= myLabel.ClientID %>").html("MY UPDATED HTML");

Upvotes: 0

NomadTraveler
NomadTraveler

Reputation: 1084

Try

$('#<%= myLabel.ClientID %>').html("here"); 
(This should work in all the browsers)

When I want to pass the value to the code behind page, I generally use a HiddenField and populate it using .val() in Jquery. I can then access its value in the code behind using HiddenField1.Value

Upvotes: 3

Terry
Terry

Reputation: 14219

Try .val() instead of .text()

Edit: Since ASP.NET controls are rendered with prefixes you may also want to consider the ends with selector.

$('span[id$="myLabel"]').val("here");

Upvotes: 0

Related Questions