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?

有帮助吗?

解决方案

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());
});

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top