I have been searching through here and google for a few days now, trying to figure out why I cannot get the value of a hiddenfield variable in javascript. When accessed, the value is returned as undefined.
I have an ASP HiddenField inside an UpdatePanel which is part of a custom user control in a .aspx web page (standard issue).
In my user control, I need to get the .Value of the HiddenField (hdnServer) in javascript after setting it in C#. But for some reason the following is not getting the correct value.
The MessageBox in the C# code returns the correct value (the code here has test values), but when accessed in javascript is undefined.
userControl.ascx:
//this function is called when the timer created in document.ready() elapses
//returns the correct hdnServer value in the check.
var checkHdn = function () {
var temp = document.getElementById("<%=hdnServer.ClientID%>").value;
temp = temp.toString();
if (temp != "") {
$('#LoadingViewer').hide();
clearInterval(checkSrv);
//enable start button
$('#startBtn').attr("Enabled", "true");
}
};
function RdpConnect() {
//serverName = undefined here. should be ip address when set in c#
var serverName = document.getElementById("<%= hdnServer.ClientID %>").value;
alert(serverName);
if (serverName != "") {
MsRdpClient.Server = serverName;
}
};
userControl.ascx.cs code-behind:
public partial class userControl : System.Web.UI.UserControl
{
System.Timers.Timer timer;
protected void Page_Load(object sender, EventArgs e)
{
timer = new System.Timers.Timer(5000);
timer.Start();
}
protected void testOnTick(object sender, System.Timers.ElapsedEventArgs e)
{
hdnServer.Value = "test value";
startBtn.Enabled = true;
timer.Enabled = false;
}
}
Here is the asp for HiddenField just in case: userControl.ascx:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<!--trigger not used -->
<!-- <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />-->
</Triggers>
<ContentTemplate>
<asp:HiddenField ID="hdnServer" runat="server" />
<asp:Label ID="Label1" Text="Loading, please wait." CssClass="loading" runat="server"
Font-Size="XX-Large" />
</ContentTemplate>
</asp:UpdatePanel>
Thank you for any advice in advance!
EDIT: messagebox removed..
Here is rendered html: http://pastie.org/3122247
You need to set ClientIDMode if you want to make it simple:
<asp:HiddenField runat="server" ClientIDMode="Static" Id="hidServer"/>
<script type="text/javascript">
alert($("#hidServer").val());
</script>
Or, use the ClientID property if you don't set ClientIDMode:
<asp:HiddenField runat="server" Id="hidServer"/>
<script type="text/javascript">
alert($("<%= hidServer.ClientID %>").val());
</script>
User controls have always been a strange issue for referencing using js and then master pages to go along with it.
For the hidden field do this:
<asp:HiddenField ID="hdnServer" runat="server" ClientIDMode="Static" />
in the js, do this:
var serverName = document.getElementById('hdnServer').value;
Try this:
var temp = $('#mytestcontrol_hdnServer').val();
you need to use ' not "
like:
var serverName = document.getElementById('<%= hdnServer.ClientID %>').value;
be careful don't use ". You have only use '
You can do this:
var temp = $('#hdnServer').val();
Instead of :
var temp = document.getElementById("<%=hdnServer.ClientID%>").value;
Also change this:
var serverName = document.getElementById("<%= hdnServer.ClientID %>").value;
To this:
var serverName = $('#hdnServer').val();
Related
UPDATE
I moved the Javascript to the ASPX site instead, and added a postback function for it. Now it works. Thanks to #orgtigger and especially #lucidgold for spending their time helping me!
Here is the update code that works!
<script type="text/javascript">
function changevalue(katoid) {
$('#<%=txtboxchosenkat.ClientID%>').val(katoid);
__doPostBack('<%= updpnlgridview.ClientID %>', '');
}
</script>
Code:
<asp:UpdatePanel ID="updpnlgridview" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="txtboxchosenkat" style="display:none;" runat="server" OnTextChanged="txtboxchosenkat_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:GridView ID="gridview" runat="server"></asp:GridView>
</ContentTemplate>
</asp:UpdatePane
Code-behind:
protected void hidfldchosenkat_ValueChanged(object sender, EventArgs e)
{
SqlConnection cn2 = new SqlConnection("Server=**,***,***,**;Database=******;
User Id=******;Password=******;");
SqlCommand cmd2 = new SqlCommand("SELECT * FROM tblProducts where KatID='" +
txtboxchosenkat.Text + "'", cn2);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.SelectCommand.CommandText = cmd2.CommandText.ToString();
DataTable dt = new DataTable();
da2.Fill(dt);
gridview.DataSource = dt.DefaultView;
gridview.DataBind();
}
The links (only part of code that makes links):
string line = String.Format("<li><a href='#' onclick='changevalue(" + pid + ");'>{0}",
menuText + "</a>");
Old Post
I need to update a GridView based on the value of a HiddenField. I am currently using a button to populate the GridView, but would like to do it automaticaly as soon as the value in the HiddenField changes.
But when I change the value with a javascript, then event doesn't fire.
(Same thing also happens in case of a TextBox and its OnTextChanged event.)
Not sure if this is way it's meant to work.
A Hidden field will not produce a postback (there is no AutoPostBack property), which means no postback will happen when the value of the hidden field has changed. However, when there is ANY postback from the page then OnValueChangd event will execute if a hidden field value has changed.
So you should try the following ideas:
1) Update your JavaScript for changevalue as follows:
function changevalue(katoid)
{
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid;
_doPostBack(); // this will force a PostBack which will trigger ServerSide OnValueChange
}
2) Change your HiddenField to a TextBox but set the Style="display:none;" and set AutoPostBack="true":
<asp:TextBox runat="server" ID="hidfldchosenkat"
Value="" Style="display:none;"
AutoPostBack="true" OnTextChanged="hidfldchosenkat_TextChanged">
</asp:TextBox>
This example works great for me:
JavaScript:
function changevalue()
{
$('#<%=hidfldchosenkat.ClientID%>').val("hi");
}
ASPX Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="hidfldchosenkat" runat="server" AutoPostBack="true"
ontextchanged="hidfldchosenkat_TextChanged"></asp:TextBox>
<asp:Button ID="Button1"
runat="server" Text="Button" OnClientClick="changevalue()" />
</ContentTemplate>
</asp:UpdatePanel>
C# Code-Behind:
protected void hidfldchosenkat_TextChanged(object sender, EventArgs e)
{
string x = "hi"; // this fires when I put a debug-point here.
}
Your issue could be with:
document.getElementById('" + hidfldchosenkat.ClientID + "').value=katoid
You may want to try:
$('#<%=hidfldchosenkat.ClientID%>').val(katoid);
Also you should PUT changevalue() inside your ASPX JavaScript tags and not register it for every LinkButton.... so instead try the following:
protected void lagerstyringgridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Assuming the LinkButtons are on the FIRST column:
LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[0];
if (lb != null)
lb.Attributes.Add("onClick", "javascript:return changevalue(this);");
}
}
You can have any event fire by doing a __doPostBack call with JavaScript. Here is an example of how I used this to allow me to send a hiddenfield value server side:
ASPX
<asp:HiddenField runat="server" ID="hfStartDate" ClientIDMode="Static" OnValueChanged="Date_ValueChanged" />
JavaScript
$('#hfStartDate').val('send this');
__doPostBack('hfStartDate');
This will call the OnValueChanged event and cause a postback. You can also set this is a trigger for an update panel if you would like to do a partial postback.
I have the following code which suppoesedly disables or enables a textbox depending on the value in a drop down list.
Now this is how I am making a reference to this code from the drop down lists:
Unfortunately, the code is generating an exception. I believe that I am using the wrong event handler, that is, OnSelectedIndexChanged. How can I remedy the situation please?
1) replace OnSelectedIndexChanged with onchange
and
2) replace
var DropDown_Total = document.getElementById("DropDown_Total")
with
var DropDown_Total = document.getElementById("<%= DropDown_Total.ClientID %>")
for all getElementById
3) replace (DropDown_Date.options[DropDown_Date.selectedIndex].value
with
(DropDown_Date.options[DropDown_Date.selectedIndex].text for both dropdown
try this it's working
<script type="text/javascript">
function DisableEnable() {
var DropDown_Total = document.getElementById("<%= DropDown_Total.ClientID %>")
var Textbox_Total = document.getElementById("<%= Textbox_Total.ClientID %>")
var DropDown_Date = document.getElementById("<%= DropDown_Date.ClientID %>")
var Textbox_Date = document.getElementById("<%= Textbox_Date.ClientID %>")
if (DropDown_Total.options[DropDown_Total.selectedIndex].text == "Any Amount") {
Textbox_Total.disabled = true;
}
else {
Textbox_Total.disabled = false;
}
if (DropDown_Date.options[DropDown_Date.selectedIndex].text == "Any Date") {
Textbox_Date.disabled = true;
}
else {
Textbox_Date.disabled = false;
}
}
</script>
html
<asp:TextBox runat="server" ID="Textbox_Total" />
<asp:TextBox runat="server" ID="Textbox_Date" />
<asp:DropDownList ID="DropDown_Total" runat="server" onchange="DisableEnable();">
<asp:ListItem>Any Amount</asp:ListItem>
<asp:ListItem>Exact Amount</asp:ListItem>
<asp:ListItem>Below Amount</asp:ListItem>
<asp:ListItem>Above Amount</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDown_Date" runat="server" onchange="DisableEnable();">
<asp:ListItem>Any Date</asp:ListItem>
<asp:ListItem>Exact Date</asp:ListItem>
<asp:ListItem>Before</asp:ListItem>
<asp:ListItem>After</asp:ListItem>
</asp:DropDownList>
Use onchange event which will work for javascript function calling. OnSelectedIndexChanged is server side event.
just replace OnSelectedIndexChanged with onchange because onchange is handled by js. OnSelectedIndexChanged is handled by code behind.
Tutorial: how to disable/enable textbox using DropDownList in Javascript
In this function we pass dropdownlist id and textbox id as parameter in js function
<script type="text/javascript">
function DisableEnableTxtbox(DropDown, txtbox) {
if (DropDown.options[DropDown.selectedIndex].text == "free") {
txtbox.disabled = true;
}
else {
txtbox.disabled = false;
}
}
</script>
Now add the following code:
<td align="center" class="line">
<asp:DropDownList ID="ddl_MonP1" runat="server" CssClass="ppup2" onchange="DisableEnableTxtbox(this,txt_MonP1);"></asp:DropDownList>
<asp:TextBox ID="txt_MonP1" runat="server" CssClass="ppup" placeholder="Subject"></asp:TextBox>
</td>
I have this function on aspx(html)
<body onload="NewPage2()">
<script type="text/javascript">
function NewPage2() {
var url = getUrlVars(url);
document.getElementById("HiddenField1").Value = url["access_token"];
}
</script>
<div class = content>
<form id="form1" runat="server">
<asp:HiddenField id="HiddenField1" runat="server" Value=""/>
</form>
CODE1: <asp:Label ID="Label1" runat="server" Text="Label" ForeColor="#CC0000" />
</div>
</div>
</body>
how can I get the var(on jquery(html)) to my variableURL2 in aspx.cs?
protected void Page_Load(object sender, EventArgs e)
{
string code = HiddenField1.Value;
Label1.Text = code;
saveToken(token, code);
}
Have one server hidden control in .aspx page
<asp:HiddenField Id="HiddenField1" runat="server"></asp:HiddenField>
in browser it will be rendered like this
<input type="hidden" id="HiddenField1" />
assign values from javascript
document.getElementById("HiddenField1").value = "your values here";
in aspx.cs render like this
string variableURL2 = HiddenField1.Value;
There are two ways you can do this, and both would have to be from a post back since the javascript is fired after the page loads.
redirect and append to the query string, then read it from c#
javascript:
location.href = "/mypage.aspx?variable2=VARFROMJAVASCRIPT";
c#
string variable2 = Request.QueryString["variable2"];
or set the value to a hidden field like above
javascript:
var $hiddenInput = $('',{type:'hidden',id:'variable2',value:'VARFROMJAVASCRIPT'});
$hiddenInput.appendTo('body');
c#
string variable2 = Request["variable2"];
.aspx:
<asp:HiddenField id="HiddenField1" runat="server" value=""/>
javascript:
function end(url) {
var url = getUrlVars(url);
var url2 = url["access_token"];
document..getElementById("HiddenField1").value = url2;
}
.cs file:
string variableURL2 = HiddenField1.Value;
Use server control HiddenField
First you have to add control in your aspx/ascx/master file
<asp:HiddenFiled ID="hdn" runat="server"/>
Then you can use this control in JS
function end(url) {
var url = getUrlVars(url);
var url2 = url["access_token"];
<%= hdn.ClientId %>.value = url["access_token"];
}
in code behind
protected void Page_Load(object sender, EventArgs e)
{
string variableURL2 = hdn.Value;
}
I have two labels:
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
and I set innerHTML by javascript:
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
How I can get those labels values in codebehind? I try:
TextBox2.Text = Label1.Text;
UPDATE:I need to get pushpin location:
<artem:GoogleMap ID="GoogleMap1" runat="server"
EnableMapTypeControl="False" MapType="Roadmap" >
</artem:GoogleMap>
<artem:GoogleMarkers ID="GoogleMarkers1" runat="server"
TargetControlID="GoogleMap1" onclientpositionchanged="handlePositionChanged">
</artem:GoogleMarkers>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<script type="text/javascript">
var list = document.getElementById("Label1");
function handlePositionChanged(sender, e) {
printEvent("Position Changed", sender, e);
}
function printEvent(name, sender, e) {
var position = e.latLng || sender.markers[e.index].getPosition();
document.getElementById('Label1').innerHTML = position.lat();
document.getElementById('Label2').innerHTML = position.lng();
}
</script>
protected void Button1_Click(object sender, EventArgs e)
{
TextBox2.Text = Label1.Text;// return value: Label
}
You cannot access the value on server side. You will have to use a hidden field for that:
<asp:HiddenField ID="Hidden1" runat="server" />
The set the innerHtml value in the Hidden field by doing:
document.getElementById('<%= Hidden1.ClientID %>').value = position.lat();
You can then access it from server side by doing:
TextBox1.Text = Hidden1.Value;
You are not able to do that with the Label control as when the page is posted back the content of labels are not posted to the server. You would need to make use of an input control of sorts. Probably a hidden input would be your best bet.
Take a hidden field like below
<asp:HiddenField ID="hdnBody" ClientIDMode="Static" runat="server" />
Then set its value in Jquery like below
<script>
function GetEmailID() {
var bodyHtml = $("#editor").html();
$("#hdnBody").val(bodyHtml);
}
</script>
And in the code behind do this to get it
string body = hdnBody.Value;
All,
I have an Update Panel control that contains a label control. I also have a Timer Control whose interval is set to 1 sec. The timer control is suppose to set the text of the label control every second with the value of a public property that changes after each iteration of the loop.
However the resulting functionality is that after the entire loop completes then the UI is updated. I'd like to know what would need to be done/coded to make sure the label control gets updated with the value of the _servername property after every iteration of the loop?
Heres my code:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="tmr" runat="server" Interval="1000" ontick="tmr_Tick">
</asp:Timer>
<div>
<asp:UpdatePanel ID="udp1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="tmr" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblInserts" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress runat="server" ID="udprg1" AssociatedUpdatePanelID="udp1"
DisplayAfter="10">
<ProgressTemplate>
<img src="media/ajaxloaderBlueLoading.gif" alt="ProgressImage" />
</ProgressTemplate>
</asp:UpdateProgress>
<div id="_asyncCallsMadeDiv"></div>
</div>
</form>
//CODE BEHIND
public string ServerName
{
get { return _serverName; }
set { _serverName = value;}
}
protected void tmr_Tick(object sender, EventArgs e)
{
lblInserts.Text = ServerName;
}
protected void btnUpload_Click(object sender, EventArgs e)
{
//Loop through data
while((line = rdr.ReadLine()) != null)
{
string [] arrayline = line.Split(',');
ServerStatus s = new ServerStatus
{
ServerName = arrayline[0],
Purpose = arrayline[1],
Primary = arrayline[2],
Secondary = arrayline[3],
OS = arrayline[4],
MachineType = arrayline[5],
Comments = arrayline[6],
VMTools = arrayline[7],
TimeSettings = arrayline[8],
LastPatchDate = arrayline[9],
CARemoval = arrayline[10],
PLUpdate = arrayline[11],
DefaultGatewayChange = arrayline[12]
};
_serverName = arrayline[0];
}
The onTick property of your timer control is set to a method that doesn't exist. You can rename tmr_Tick method in your code behind to tmrUdp1_Tick or set the onTick property to tmr_Tick