Search code examples
javascriptasp.nettextboxhidden-field

How to get the text from <input hidden> in code-behind?


I have two fields in an aspx file:

<input type="text" id="tbName" runat="server"/> 
<input type="hidden" id="hfName" runat="server"/>

The idea is to use text from textbox "tbName" as a parameter for my stored procedure. I decided to add its text to a hidden field "hfName" using javascript:

document.getElementById("<%= hfName.ClientID %>").value = document.getElementById("<%= tbName.ClientID %>").value;
alert(document.getElementById("<%= hfName.ClientID %>").value);

It works well and hidden field takes the text from the textbox, the function alerts about it. I use hidden field because this is the only way for me to save the text during postback.

In code-behind I try to get hidden value from hfName.Value back to the textbox, but it returns empty line:

tbName.Value = hfName.Value;

So how to use it as a parameter? Maybe there is an easier way? I don't know jquery.


Solution

  • In the main Page_Load procedure I put tbName.Value = hfName.Value; This is the only place where I try to use value from hidden field hfName.Value. tbName is not modified after it and should show the text from hidden field hfName. It doesn't.

    when page loading nothing set as textbox text, so tbName and hfName values are empty.

    you can test this by set default values to both hidden and text fields

    <input type="text" id="tbName" runat="server" value ="txtVal"/> 
    <input type="hidden" id="hfName" runat="server" value ="hftVal"/>
    

    now on page load you can get non empty values of both controls

    protected void Page_Load(object sender, EventArgs e)
    {
        var txtVal = tbName.Value;
        var hfVal = hfName.Value;
    }