Why can I access asp: TextBox in javascript but not asp: Label?

Here's a simple demo of what I'm talking about

js in the header header:

  function changeTxt(frm){
    var lblo = frm.txt1;
    lblo.value = "hey guy";

    var lbl = frm.lblStatus;
    lbl.innerHTML = "hello world";
  }

      

aspx / html markup:

<asp:Label ID="lblStatus" runat="server"></asp:Label>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>

<button onclick="changeTxt(this.form);">go</button>

      

js finds the element txt1

( input

html) and changes the value. But why can't it find the element lblStatus

( span

html)? It appears as undefined

. They are all in one form.

Edit: It seems the problem is with nodes span

in js. I think you cannot access them through the form object like I do.

+3


source to share


2 answers


asp:Label

is displayed as a range or label, so value

it is not the correct way to change the text. You will need to use something like innerHTML

Like this:

function changeTxt(frm){
    var lblo = document.getElementById('<%: txt1.ClientID %>');
    lblo.value = "hey guy";

    var lbl = document.getElementById('<%: lblStatus.ClientID %>');
    lbl.innerHTML = "hello world";
}

      



You should also use getElementById

to get the object.

Watch out for potential XSS problem when using innerHTML

.

+3


source


ASP:Label

does not render the form element. It displays span

or label

. You have to access the value using innerHTML. Be sure to use the ClientID because the ASP.NET runtime may display a different identifier if the label control is not directly on the page or if you are using the master page.



var lbl = document.getElementById("<%= lblStatus.ClientID %>");
lbl.innerHTML = "hello world";

      

+2


source







All Articles