[javascript] Set Text property of asp:label in Javascript PROPER way

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.

This question is related to javascript asp.net label code-behind

The answer is


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!


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.:';
         } 
     }

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 :)


Use the following code

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

Java Script

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

C#

sptext.innerHTML

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.


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" />

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to label

How to set label size in Bootstrap How do I change the text size in a label widget, python tkinter Change grid interval and specify tick labels in Matplotlib Editing legend (text) labels in ggplot How to change Label Value using javascript React ignores 'for' attribute of the label element How to dynamically update labels captions in VBA form? why I can't get value of label with jquery and javascript? What does "for" attribute do in HTML <label> tag? Get Application Name/ Label via ADB Shell or Terminal

Examples related to code-behind

How to call a C# function from JavaScript? how to access master page control from content page Set Text property of asp:label in Javascript PROPER way ASP.NET Web Application Message Box How to programmatically set the Image source Accessing a resource via codebehind in WPF Adding css class through aspx code behind Passing arguments to JavaScript function from code-behind The name 'controlname' does not exist in the current context ASP.net page without a code behind