[RESOLVED]No output to the label

This javascript function doesn’t assign to the label. Can you help? Thanks.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">

    <asp:Button ID="Button1" runat="server" OnClientClick= "myFunction(6,7)" Text="Button" />

    <asp:Label runat = "server" ID= "thisone"></asp:Label>
<script type="text/javascript">
    function myFunction(x, y) {
        document.getElementById("thisone").text = x + y;
        return false;}


Change this to

 document.getElementById("<%= thisone.ClientID %>").innerHTML = (+x) + (+y);

Also to make sure your x+y to be an integer you can even use parseInt statements to make it to number. I’ve used unary plus operator.



document.getElementById("thisone").innerHTML= x + y;

Thank you. The label is loading for just a brief instant then it’s blank again. I suspect a postback but I don’t have any code behind.

Can I fix it so that the label value remains?

Change your function call like given below

 <asp:Button ID="Button1" runat="server" OnClientClick="return myFunction(6,7)" Text="Button" />

Complete Code:

<asp:Button ID="Button1" runat="server" OnClientClick="return myFunction(6,7)" Text="Button" />
        <asp:Label runat="server" ID="thisone"></asp:Label>
        <script type="text/javascript">
            function myFunction(x, y) {
                document.getElementById("thisone").innerHTML = x + y;
                return false;


As the others mentioned, whenever referencing an actual ASP.NET Control within your Javascript code, it’s always safer to use the

ClientID property
. This property will provide you with the exact ID value that is rendered on the client and you’ll be able to use it to target your actual Control within Javascript :

// Use the ClientID to reference your field and the innerHTML attribute to set your value
document.getElementById("<%= thisone.ClientID").innerHTML = x + y;

You mentioned a flickering that was occuring when your button was pressed. This is because by default a PostBack is going to occur for ASP.NET Button elements when they are clicked. You can prevent this by adding a "return" statement prior to your function
call as seen below :

<asp:Button ID="Button1" runat="server" OnClientClick= "return myFunction(6,7);" Text="Button" />

This will hit the "return false" statement in your function and prevent the PostBack behavior from occurring. You can see an example below which has no flicker and uses the same markup changes mentioned :

Thanks guys.

Leave a Reply