views:

376

answers:

2

In jquery how do you save variable which can only be true/false into a hidden field and retrieve a value after postback?

+2  A: 

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.

Guffa
Thanks for the reply, I'll turn it into HiddenField control and give it a try
Victor
+2  A: 

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.

benjynito
+1 for remembering to use .ClientID :-)
roufamatic