Reputation: 941
In jquery how do you save variable which can only be true/false into a hidden field and retrieve a value after postback?
Upvotes: 1
Views: 4274
Reputation: 4085
Given an input with the runat="server" set as so:
<input type="hidden" runat="server" id="hdnValue" value="0" />
or
<asp:HiddenField runat="server" id="hdnValue" ... />
use the following script
var hiddenValue;
// On load
$(function()
{
// Get hidden field by ID
hiddenValue = $('#<%= hdnValue.ClientID %>');
// Get value
var value = hiddenValue.val();
alert(value);
// Set value
hiddenValue.val(1);
alert(hiddenValue.val());
});
Note that Boolean won't parse an asp.Net bool.ToString() as anything but true. If you use them you'll want to write a small function to check for value.toLowerCase() == "true" before assuming you have a true value.
Upvotes: 3
Reputation: 700212
The jQuery part is nothing special, just put some textual representation of the value in the field, and later read it from the field:
$('#myHiddenField').val(myBoolean?'1':'0');
myBoolean = $('#myhiddenField').val() == '1';
However, the value in a hidden field doesn't survive the postback by itself. You either have to turn the field into a server control using runat="server"
, change it for a HiddenField control, or read the value from Request.Form or Request.QueryString and put the value in the field that is put in the new page.
Upvotes: 3