Click here to Skip to main content
15,921,716 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a asp hidden field on my web form. I set the hidden field value from the code behind. I want to access this value from a javascript function in external .js file.

This is the asp hidden field
C#
<asp:HiddenField ID="HiddenField1" runat="server" />


I set the value in code behind
JavaScript
HiddenField1.Value = "xyz";


How can I access HiddenField1.value in external .js file.

Give me example...

Thanks
Anand

What I have tried:

var hf=document.getElementById('HiddenField1').value; 
Posted
Updated 15-Oct-19 23:08pm
v2

1 solution

<form runat="server">
    <asp:HiddenField ID="HiddenField1" runat="server" />
</form>

<script>
    var hiddenFieldId = '<%= HiddenField1.ClientID%>';
</script>

<script src="test.js"></script>


test.js

if (typeof hiddenFieldId !== 'undefined') {
    var el = document.getElementById(hiddenFieldId);

    alert(el.value);
}


There is probably a better solution depending on what your javascript is doing though. If you're writing js components that attach to elements it's generally better to read the required ids from data attributes, or to target items in your js via attributes rather than IDs

<form runat="server">
    <input type="hidden" id="HiddenField1" data-targetid runat="server" />
</form>

<script src="test.js"></script>


test.js

var el = document.querySelector("[data-targetid]");

alert(el.value);
 
Share this answer
 
Comments
[no name] 17-Oct-19 0:00am    
Thank you sir...!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900