Friday, May 18, 2012

Read hidden field value in from jquery

Often we are confused about how to read values set in HiddenField from jquery and use the values in the web form. Many-a-times we see the threads over the forums about the difficulties associated with reading HiddenField values. I have tried to give easy and fast way to read values and set values of hidden filed in using jquery.
You may first download the latest jquery file from webform - design page
    <form id=\"form1\" runat=\"server\">
    <asp:HiddenField ID=\"HiddenField1\" runat=\"server\" />
    <asp:Label ID=\"lblSiteName\" runat=\"server\"></asp:Label>
    <script type=\"text/javascript\" src=\"js/jquery-1.3.2.min.js\"></script>
    <script type=\"text/javascript\">
        $(function () {
            //reading hidden field value
            var mySite = $(\'#HiddenField1\').val();
            //displaying the value in an Label control
            $(\'#lblSiteName\').html(\'My site is: \' + mySite);
            //setting value of HiddenField control
            $(\'#HiddenField1\').val(\'New site is:\')
</body> webform - code page (in c#)
protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            HiddenField1.Value = "";
Known issue
If you have put the HiddenField control below the script tags, you may end up reading 'undefined' values. To solve the issue, I recommend putting the hidden fields at the top of the page just below the form tag.
Further, if you are using Master Page, please make changes in the jquery codes respectively. In such case, I  recommend the following syntax:
var mySite=$('[id$=HiddenField1]').val();
The system $= means the value that end with HiddenField1. This works since you usually see the id HiddenFiled1 used with master page rendered as ctl00_ContentPlaceholder1_HiddenField1.

Happy programming!!
Shout it


Anonymous said...

very usefull

lulur bali alus said...

salam kenal bos. lagi jalan jalan pagi nih

gokul said...

Nice article... on fetching the hidden field value.
Would like to add few more points:
1. Hidden field values altered at client side are accessible because it is stored in an encoded format in ViewState.
2. Always use clientID to access the control's Id instead of using
var mySite=$('[id$=HiddenField1]').val();

var hiddenField1= document.getElementById(‘<%=HiddenField1.ClientID %>’);

Click here to

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles