开发者

jQuery hidden field

开发者 https://www.devze.com 2022-12-18 22:57 出处:网络
In jquery how do you save variable which can only be true/false into a hidden field and retrieve a value开发者_C百科 after postback?The jQuery part is nothing special, just put some textual representa

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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消