3

I want to add a table element after a specific element after an element run at the server but when I tried to access the id of the element it was treated as a string

I have tried showing the id or an element in an alert but it is string I have tried to check for other posts on stack overflow but they all say the way to access is the same way that for me produces strings I have tried putting the same code as in the string in the aspx file and it works so I know there isn't a problem with the <%=message.ClientID%>

in aspx file

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="Manager">
        <p id="message" runat="server" class="caption">
            There aren't any users in the database
        </p>
        <form runat="server">
            <asp:HiddenField id="hfData" runat="server"/>
        </form>
        <script src="js/Manager.js" ></script>
    </div>
</asp:Content>

in Manager.js

var message = document.getElementById('<%=message.ClientID %>');
message.parentNode.insertBefore(tbl, message.nextSibling);

message equals to undefined when i watch it's value and the following code doesn't execute

I have tried the following to try access the id

var str = '<%=message.ClientID%>';
alert(str);

but it alerts <%=message.ClientID%> as a string It should produce the output of ContentPlaceHolder1_message

2 Answers 2

4

First, try to add the Manager.js script directly to the aspx page, which worked for me. I am afraid when the .aspx page is executed on the server at that moment, Manager.js is not included as the page is rendered.

<p id="message" runat="server" class="caption">
     There aren't any users in the database
</p>
<script type="text/javascript">
     var str = '<%=message.ClientID%>';
     alert(str);
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

I now got what you meant thanks, is there any way to make the script rendered for the first time at the server side and save the Id in a variable?
I am glad i was on any help
1

I managed to solve the problem by creating a javascript variable on the server side with razor code and then using it in the external javascript file

in aspx

<script type="text/javascript">
    var messageId = '<%=message.ClientID%>';
</script>

in Manager.js

var message = document.getElementById(messageId);
message.parentNode.insertBefore(tbl, message.nextSibling);

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.