问题
My second question today. I got really stuck. Ok, 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 not to lose the textbox text and use it as a parameter? Maybe there is an easier way? I don't know jquery.
回答1:
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;
}
回答2:
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());
来源:https://stackoverflow.com/questions/16141847/how-to-get-the-text-from-input-hidden-in-code-behind