Angwenyi
Angwenyi

Reputation: 329

How do you set ASP.net html control(label) using javaScript

I have created a JavaScript function to get the type of html control and set it to specified value.

function SetControlValue(ctrl, value) {

if (value == undefined)
    return "";

if (document.getElementById(ctrl).type == "text") {
    document.getElementById(ctrl).value = value;
}


else if (document.getElementById(ctrl).type == "label") {

   //document.getElementById(ctrl).innerText = value;
   document.getElementById(ctrl).innerHTML = value;      

} 

return false;

}

On my ASPX page i have created a label as below

<asp:Label id="lblMessage" class="labels"Font-Size="Medium" runat="server"></asp:Label>

and now calling the function

var don="sample text";

SetControlValue('lblMessage', don)

My question is why SetControlValue() function working on text fields but does not work on labels. Is there something that am missing? Thanks.

Upvotes: 0

Views: 1887

Answers (2)

Dieterg
Dieterg

Reputation: 16368

The reason why it's not working is because ASP changes the ID of your label. You'll need to get the client side id of the label control.

SetControlValue('<%= lblMessage.ClientID %>', value);

As @Tim B James suggested in the comments you can also set the ClientIDMode to Static as follows:

<asp:Label ClientIDMode="static" id="lblMessage" class="labels" Font-Size="Medium" runat="server"></asp:Label>

Edit: Basically you don't need to check for label or span. Instead you can check if your div element has a property called innerHTML or value. I suggest you to change the javascript function to the following and it should work:

function SetControlValue(ctrl, value) {

    if (value == undefined) {
        return "no value set";
    }

    var element = document.getElementById(ctrl);

    if(!element) {
        return "element not found";
    }

    if(element['value'] !== undefined) {
        element['value'] = value;   
    } else if (element['innerHTML'] !== undefined) {
        element['innerHTML'] = value;   
    }

    return false;
}

Fiddle

Upvotes: 3

SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6056

Try this:

document.getElementById(ctrl).innerHTML = value;

Update:

When a asp.net label control is rendered it is Rendered as <span> and not aslabel.

    function SetControlValue(msg) {
    document.getElementById('<%= Label1.ClientID %>').innerHTML = msg;
    var control = document.getElementById('<%= Label1.ClientID %>');
    if (control != null && control.nodeName == "span") {
      alert("its label control");
    }

This works for me!

NOTE: Please make changes in the function according to your needs!

Upvotes: 0

Related Questions