2

For the sake of testing im creating a button that will hide a text box when clicked. The javascript for the button press looks like:

function showCommentBox() {
    var el = document.getElementById('replyBox');
    el.setAttribute("style", "display:none;");
    return false;
}

The asp code looks like:

<textarea  id="replyBox" runat="server" class="replyBox"></textarea>
<asp:Button runat="server" id="replyBtn" onClientClick="return showCommentBox();" class="replyBtnClass" Font-Bold="true" Text="Reply"/>

It seems that whenever I try modifying an element running on server it causes a postback. Is there something wrong with my logic or is this just not posible?

0

2 Answers 2

2

If you look at the generated id of the server control, you will notice it is different than what you set it as. The id you are setting is the code-behind ID. When the page is rendered, the element is assigned its ClientID. This is why you are having the problem.

You have two choices:

  1. Set the ClientIDMode to "static". This will preserve the id of the element to exactly what you set it to. Make sure to only do this if you will only have one element with this ID. Otherwise your javascript will start acting strangely.

  2. Set the id for the javascript dynamically. Like this:

    document.getElementById('<% replyBox.ClientID %>');

This will inject the ClientID of the rendered server control directly into the javascript. Note: this will only work if the javascript is in the aspx page. IF the javascript is moved to a js file, this will not work.

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent it worked. Also loads of info I didn't know thank you.
Glad to help. Which method did you implement?
I used the ClientIDMode for a while until I realized It would be better to encase the box and other stuff with a div tag and hide that all of it in one go. Should I have gone that route at first I would't of found out about this stuff though so thanks again.
1

This line would return undefined in your case

var el = document.getElementById('replyBox');

As you are using replyBox as Id of textarea with runat="server" attribute. Either you need to use ClientIdMode="Static" or refer ClientId of textarea in your function like this

document.getElementById('<% replyBox.ClientID %>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.