开发者

How to set the text of a button using JScript?

I'm trying to set the text on a button in a JScript function. I am using a JScript function like this...

    function myfunction(sender, eventArgs)
    {
        wanted_text = window.source_text_field.get_displayText();

        if (document.getElementById("my_span_element") != null)
        {
            document.getElementById("my_span_element").innerText = wanted_text;
        }

        if (document.getElementById("my_button") != nu开发者_Python百科ll)
        {
            document.getElementById("my_button").text = wanted_text;
        }

    }

where the controls concerned are define like this...

    <span id="my_span_element" class="some_class"></span>

    <asp:Button id="my_button"
                runat="server"
                class="some_other_class"
                text=""
                Width="48"
                Height="25"
                onclick="do_foo"/>

The text in the span element is set correctly but the button is unaffected. I've also tried innerText, Value, Text, and also attempted to use the answer to this question but to no avail.

Can anyone see what I have overlooked?


Change the .value attribute of button:

document.getElementById("my_button").value = "new value";


ASP.Net generates its own IDs for server controls.

You need to write <%= my_button.ClientID %> to get this generated ID.


There are 2 problems here:

First: you use wrong attribute - should be "value", instead of "text"

Second: document.getElementById("my_button") will not work because ASP.NET assigns it's own ids to controls. If you take a look at generated markup you will notice that id of the element is completely different.

If your javascript is inside of the same .aspx page as <asp:button /> control, you can do like this:

document.getElementById("<%= my_button.ClientID %>").value = "some text";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜