sw2020
sw2020

Reputation: 195

Passing ASP.NET label id to Javascript

I can get the Label value to change when I use the following code

  document.getElementById('<%=lblDropdownValue.ClientID %>').innerHTML =     ddl.value;

But I would like to pass it as a parameter as shown below, but it does not seem to work.

<table>
    <tbody>
        <tr>
            <td>
              <asp:DropDownList id="ddlProducts" runat="server" 
           onclick="myfunction(this,'<%=lblDropdownValue.ClientID %> "')">

                <asp:ListItem Selected="True" Value="-1"> Please Select </asp:ListItem>
                <asp:ListItem Value="Car"> BMW </asp:ListItem>
                <asp:ListItem Value="Music"> MP3 </asp:ListItem>

             </asp:DropDownList>

           </td>
           <td>
               <asp:Label Text="" id="lblDropdownValue" runat="server"/>
           </td><td></td>
       </tr>

   </tbody>

</table>
</div>
</form>
<script>
   function myfunction(ddl, lblText)
   {
      document.getElementById("'"+lblText+"'").innerHTML = ddl.value;          
   }
</script>

Upvotes: 1

Views: 85

Answers (2)

sw2020
sw2020

Reputation: 195

In the code behind I added

   protected void Page_Load(object sender, EventArgs e)
        {
            ddlProducts.Attributes["onclick"] = "myfunction(this,"+lblDropdownValue.ClientID +");";

        }

And Changed the JavaScript to

 <script>
        function myfunction(ddl, lblText)
        {            
           lblText.innerHTML
            = ddl.value;          
        }
    </script>

Upvotes: 1

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

Put this in the code behind:

public void Page_Load( ... ) {

    ddlProducts.Attributes["onclick"] = "myfunction(...)";

}

and remove the onclick from the ASPX.

The reason for this is that you want the onclick to be attached at the client side. What you now have is an attribute that is evaluated server side and thus it doesn't make it properly to the client.

Upvotes: 1

Related Questions