简体   繁体   中英

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.

In your JavaScript part you write the value from tbName to hfName, in the code behind from hfName to tbName.

hfName.Value = tbName.Value;

With jQuery you could solve the client side part like

$("#<%= hfName.ClientID %>").val($("#<%= tbName.ClientID %>").val());
alert($("#<%= hfName.ClientID %>").val());

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM