Set Text property of asp:label in Javascript PROPER way
Asked Answered
D

7

24

I have a series of textboxes on a form. When the user inserts numbers into these textboxes, calculations are made and <asp:Label> controls are updated via JavaScript to reflect these calculations:

document.getElementById('<%=TotalLoans.ClientID %>').innerHTML = TotalLoans;

This correctly updates the UI. However, when I try to access the value in the codebehind, the Text property is empty. This makes sense I guess, since I was updating the innerHTML property via the JavaScript.

//TotalLoans.Text will always be equal to "" in this scenario
double bTotalLoans = string.IsNullOrEmpty(TotalLoans.Text) 
                   ? 0.00 
                   : Convert.ToDouble(TotalLoans.Text);

How do I update the Text property of the <asp:Label> via JavaScript in such a way that I can read the property in the codebehind?

Update

This is a small problem on a large form that contains 41 labels, each of which displays the results of some calculation for the user. Taking the advice of FishBasketGordo I converted my <asp:Label> to a disabled <asp:TextBox>. I'm setting the value of the new textbox as such:

    document.getElementById('<%=TotalLoans.ClientID %>').value = TotalLoans;

Again, in the codebehind, the value of TotalLoans.Text is always equal to "".


I don't mind changing how I approach this, but here's the crux of the matter.

I am using JavaScript to manipulate the property values of some controls. I need to be able to access these manipulated values from the code behind when 'Submit' is clicked.

Any advice how I can go about this?

Update 2

Regarding the answer by @James Johnson, I am not able to retrieve the value using .innerText property as suggested. I have EnableViewState set to true on the <asp:Label>. Is there something else I am missing?

I don't understand why, when I type in a textbox and submit the form, I can access the value in the codebehind, but when I programmatically change the text of a textbox or label by way of JavaScript, I cannot access the new value.

Desmid answered 12/4, 2012 at 17:17 Comment(5)
It might not be possible because an asp:Label isn't a type of <input>. I feel like I've run into this before and had to use hidden inputs for the server to recognize it.Henandchickens
What you are doing will work after a postback occurs. Asp.net/Server doesn't know if anything changed until it gets another chance to look at it.Polyphonic
Although you could possibly make them work, <asp:Label> controls aren't really the right choice for what you're doing. I would consider using a read-only textbox or something more semantically appropriate.Respecting
Thanks FishBasketGordo, please see updateDesmid
@splatto: Updated my answer. I think I've found a good solution for you.Yester
I
18

Place HiddenField Control in your Form.

<asp:HiddenField ID="hidden" runat="server" />

Create a Property in the Form

protected String LabelProperty
{
    get
    {
        return hidden.Value;
    }
    set
    {
        hidden.Value = value;
    }
}

Update the Hidden Field value from JavaScript

<script>
   function UpdateControl() {
            document.getElementById('<%=hidden.ClientID %>').value = '12';
   }
</script>

Now you can access the Property directly across the Postback. The Label Control updated value will be Lost across PostBack in case it is being used directly in code behind .

Ist answered 12/4, 2012 at 17:53 Comment(5)
@James Johnson, I tried to post this on your answer. I am not able to retrieve the value using .innerText property. I have EnableViewState set to true on the <asp:Label>. Is there something else I am missing?Desmid
I cannot access the Label updated value across Postback as it will be lost during postback. So, I need to use ViewState/HiddenField Control.Ist
@PankajGarg: You were actually right. I was thinking that the value could be stored in an attribute of the label, but it is not.Yester
@John: I did make a mistake regarding the label, but being that I'm in the top 0.001% of ASP.NET users on the site, I don't think it's fair to say that I have no understanding of ASP.NET. I appreciate your comment though :)Yester
This solution works great. However, actually selecting an ASP.NET hidden field can be a problem with an external JavaScript file and jQuery. This answer has the solution to that.Argue
N
5

This one Works for me with asp label control.

 function changeEmaillbl() {


         if (document.getElementById('<%=rbAgency.ClientID%>').checked = true) {
             document.getElementById('<%=lblUsername.ClientID%>').innerHTML = 'Accredited No.:';
         } 
     }
Nerveracking answered 15/9, 2015 at 5:22 Comment(0)
A
3

Use the following code

<span id="sptext" runat="server"></span>

Java Script

document.getElementById('<%=sptext'%>).innerHTML='change text';

C#

sptext.innerHTML
Attention answered 8/5, 2012 at 9:38 Comment(1)
The correct syntax is ---- document.getElementById("<%=sptext.ClientID%>").innerHTML= "change text";Fin
Y
2

Instead of using a Label use a text input:

<script type="text/javascript">
    onChange = function(ctrl) {
        var txt = document.getElementById("<%= txtResult.ClientID %>");
        if (txt){
            txt.value = ctrl.value;
        }           
    }
</script>

<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />      

<!-- pseudo label that will survive postback -->  
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />        

<asp:Button ID="btnTest" runat="server" Text="Test" />
Yester answered 12/4, 2012 at 17:21 Comment(1)
Although it solves the OP's problem it causes another one. The text input can be selected by the mouse. This gives the appearance the field is updatable. Then if the backspace button is clicked, IE navigates to the previous page. Farewell to the data that was in the form.Argue
S
1

Since you have updated your label client side, you'll need a post-back in order for you're server side code to reflect the changes.

If you do not know how to do this, here is how I've gone about it in the past.

Create a hidden field:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />

Create a button that has both client side and server side functions attached to it. You're client side function will populate your hidden field, and the server side will read it. Be sure you're client side is being called first.

<asp:Button ID="_Submit" runat="server" Text="Submit Button" OnClientClick="TestSubmit();" OnClick="_Submit_Click" />

Javascript Client Side Function:

function TestSubmit() {
              try {

             var message = "Message to Pass";
             document.getElementById('__EVENTTARGET').value = message;

           } catch (err) {
              alert(err.message);

          }

      }

C# Server Side Function

protected void _Submit_Click(object sender, EventArgs e)
{
     // Hidden Value after postback
     string hiddenVal= Request.Form["__EVENTTARGET"];
}

Hope this helps!

Sharpwitted answered 12/4, 2012 at 17:26 Comment(0)
B
1

Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.

So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)

Billon answered 12/4, 2012 at 17:34 Comment(0)
M
0

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

Macaronic answered 12/4, 2012 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.