问题
I have a hidden field in my form, I'm setting the hidden field's value on the server and trying to access this value from javascript,
I get the error: Unable to get value of the property 'value': object is null or undefined
If I view the source the hidden field value is set and the ID of the hidden field is the same as the ID I'm calling.
ASPX
var v = document.getElementById('hxValue').value;
<asp:HiddenField ID="hxValue" runat="server"/>
VB
hxValue.Value = "Value1"
I recall doing this before and it should be relatively simple but for some reason, i'm not getting it right.
回答1:
Your code will work. For simple forms, just add
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
OR
you need to find the client id using
'<%=hxValue.ClientID%>'
回答2:
Ok it appears my hidden field's value had not been set before the script had run, therefore receiving a null value. I had assumed that placing breakpoints on the server page load and the script would establish if the control was being set before the script ran, appears not.
Fixed as below:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script type="text/javascript">
function GetHiddenValues() {
var v = document.getElementById('<%= hxValue.ClientID %>').value;
}
</script>
</head>
<body onload="GetHiddenValues() ;">
<form runat="server">
<asp:HiddenField ClientIDMode="static" ID="hxValue" runat="server"/>
</form>
</body>
</html>
Thanks for all the assistance.
回答3:
You can use innerText
not value
to retrieve the value of hxValue.
var v = document.getElementById('hxValue').innerText
If you were using jQuery
you could also do
var v = $("#hxValue").val();
回答4:
Try <asp:HiddenField ID="hxValue" runat="server" Value=""/>
Then call it by id and set value
回答5:
Try this
var v = document.getElementById('<%= hxValue.ClientID %>').value;
Problem is that Hidden Field is server side control and it's ID that you have given is a server side ID, you will have to get client side ID of that control to refer it in your client side JavaScript or Jquery.
Update
put this script at the end of your page, just before </body>
something like this
<script type="text/javascript" language="javascript">
var v = document.getElementById('<%= hxValue.ClientID %>').value;
</script>
</body>
来源:https://stackoverflow.com/questions/13579995/accessing-hidden-field-value-in-javascript