Pregunta

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?

¿Fue útil?

Solución

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top