Set ASP.NET Label text with Javascript

The ASP label id is Label1 and the ClientID in javascript is just need to be there. You cannot do

 

document.getElementById(“Label1”).innerHTML = SelValue;

 

it just won’t work.

 

What you need is

 

document.getElementById(<%= Label1.ClientID %>).innerHTML = SelValue;

 

The complete code is like below.

 

<%@PageLanguage=”C#”AutoEventWireup=”true”CodeBehind=”WebForm1.aspx.cs”Inherits=”WebAppJSDropDown.WebForm1″%>

 

<!DOCTYPEhtmlPUBLIC“-//W3C//DTD XHTML 1.0 Transitional//EN”http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<htmlxmlns=”http://www.w3.org/1999/xhtml”&gt;

<headrunat=”server”>

  <title></title>

</head>

<body>

  <scriptlanguage=”javascript”>

 

    function OnChange(dropdown) {

      var myindex = dropdown.selectedIndex;

      var SelValue = dropdown.options[myindex].value;

 

      document.getElementById(<%= Label1.ClientID %>).innerHTML = SelValue;

      returntrue;   

    }

 

  </script>

  <formid=”form1″runat=”server”>

  <div>

    <asp:LabelID=”Label1″runat=”server”Text=”Label”></asp:Label>

    <selectname=”select1″onchange=’OnChange(this.form.select1);’>

      <option>Value 1</option>

      <option>Value 2</option>

      <option>Value 3</option>

    </select>

  </div>

  </form>

</body>

</html>

 

You can also download a single solution from http://skydrive.live.com. The sample file name is WebAppJSDropDown.rar My MSN ID is chanmmn@hotmail.com.

Resources:

http://stackoverflow.com/questions/4946013/set-asp-literal-text-with-javascript

About chanmingman

Ming Man is a senior manager for a development company. With 20 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s