tags:

views:

66

answers:

4

Hello All,

I have written javascript function in my view page but it is giving me an error.I wnat to set the selected value of dropdown in the label.Please tell me where am I going wrong??

    function OnSelect()
    {

        var label = document.getElementById("<%= lblSelection.ClientID %>");
        label .Text= "You selected <b>";

    }

Above is the script function

+5  A: 

There is no text property on an element. Assuming the element refered to using label is something like a div or span, use:

function OnSelect()
{
    var label = document.getElementById("<%= lblSelection.ClientID %>");
    label.innerHTML = "You selected <b>";
}
stefpet
A: 

Mixing Server and Client

Property Text is only available on the server Label control, but not on the client DOM element. You've mixed this a bit.

Avoid server controls in MVC

Even though you shouldn't use Asp.net web server controls with a MVC application. It's not recommended. They can be used but with caution. In your case where you don't distinguish between server and client controls I assume you're rather a beginner. No offence but I suggest you rather start and learn pure and clean MVC applications first before doing this kind of mix.

Robert Koritnik
A: 

You seem to be confusing an asp:Label control on the server-side with a DOMElement on the client side. Take some time to learn the JavaScript environment and the DOM API. Then learn jQuery, which wraps the different DOM implementations with a very nice and consistent API.

Also When using MVC you shouldn't use WebForms controls unless you need to. This makes it much easier to understand what's going on in the client-side of things when your JavaScript is running.

wm_eddie
A: 

As others have pointed out, Text is not a valid DOM property. You may be thinking of the text method that jQuery provides to set the innerHTML of an element as plain text.

However, you also end your string in with the bold tag, which leads me to believe that you plan on building out an HTML string with more content. If this is the case, you should use the following approach and build out the entire HTML string, and then update the DOM element.

var OnSelect = function() {
    var html = "You selected <b>";

    if ( someCondition ) {
        html += "some value";
    }

    html += "</b>";

    $("<%= lblSelection.ClientID %>").html(html);
};

On the other hand, if you mean to literally display You have selected <b>, and <b> is not supposed to be an HTML tag, then you'll need to do the following:

var OnSelect = function() {
    $("<%= lblSelection.ClientID %>").text("You selected <b>");
};

Notice the use of text rather than html.

Justin Johnson