1

I am very confused when it comes to using asp:hiddenfields .

Here is my code:

<asp:HiddenField ID ="CurrentAnswer" runat="server" Value="-1" />

and in a js file loaded in that html page:

$(document).ready(function () {
    alert(document.getElementById("<%= CurrentAnswer.ClientID %>"));
});

This value returns null. It will work if i put it into the same asp webform, but not in a separate js file.I have seen this done on just about every page I looked at. here for example. I have no idea why this is not working. Any thoughts?

2

2 Answers 2

4

If you want to keep the javascript in sepearate js file, you want to use Static (or Predictable) for ID.

<asp:HiddenField ID="CurrentAnswer" runat="server" Value="-1" 
   ClientIDMode="Static" />

Separate JavaScript File

$(document).ready(function () {
    alert($("#CurrentAnswer").val());
});
Sign up to request clarification or add additional context in comments.

Comments

0

If the CurrentAnswer ID is not dynamic, you can do this:

$(document).ready(function () {
    alert(document.getElementById("CurrentAnswer"));
});

Of course, this will give you an object, so you can call .val() to get the value of it.

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.