Accessing hidden field value in javascript

2019-07-11 19:11发布

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.

5条回答
走好不送
2楼-- · 2019-07-11 19:30

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();
查看更多
该账号已被封号
3楼-- · 2019-07-11 19:31

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>
查看更多
太酷不给撩
4楼-- · 2019-07-11 19:34

Try <asp:HiddenField ID="hxValue" runat="server" Value=""/>
Then call it by id and set value

查看更多
ゆ 、 Hurt°
5楼-- · 2019-07-11 19:36

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.

查看更多
做个烂人
6楼-- · 2019-07-11 19:51

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%>'
查看更多
登录 后发表回答