Getting hidden variable value from server side in client side

hi,

        I am struck in problem. I have a hidden field in my form and i am setting some value in that.

         Now i wnt to use this value from client side but i m not able to retrieve it. All i am getting there is an object.

         I feel the hidden field is not able to hold that value.

         <input type="hidden" id="hdnVar" runat="server" />

         in code behind

         hdnVar.Value = "abc";

         client side

         alert('value '+document.getElementById('<%= hdnVar.ClientID %>'));

         alert only shows string value not the value of hidden field
 

0
pankajsachdeva
6/20/2008 6:15:47 AM
asp.net.getting-started 91979 articles. 3 followers. Follow

13 Replies
1106 Views

Similar Articles

[PageSpeed] 34

document.getElementById will give you a reference to the element itself, not just the value. Try this instead (you were almost there):

alert('value '+document.getElementById('<%= hdnVar.ClientID %>').value);


"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
6/20/2008 8:02:22 AM

 Thanx for reply

    I tried that but somehow the hidden variable is not taking any value.

   When i tried to insert value in the hidden variable at Page Load it is displaying it. But when i used it in a function and using it on the post back it is not retaining the value and the alert is showing null value to me. Why is it not retaining the values assigned to it in post back?

I have checked it using debugger it is picking the value at runtime but some how it is being lost when i try to use it on the client side.
 

0
pankajsachdeva
6/20/2008 8:28:04 AM
Are you setting the value on the client-side or on the server? Can you post up the relevant code to show how you're setting the value as it might make it easier to see any problems.

"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
6/20/2008 8:32:34 AM

 Here is my code:

    Client Side

    alert('hidden '+document.getElementById('<%= hdnVar.ClientID %>').value); 

    Code Behind 

    public string GetImage(int index)
    {
       
        string path = "Gallery\\Gallery1\\";
        string[] files;
        files = Directory.GetFiles(Server.MapPath(path), "*.jpg");
        hdnVar.Value = files.Length.ToString();
        if (index > files.Length)
            return "DEC";
        if (index < 0)
        {
            return CreateImageTags(path, System.IO.Path.GetFileName(files[files.Length + index]));
        }
       
        if (index == files.Length)
            return "Last";
        return CreateImageTags(path, System.IO.Path.GetFileName(files[index]));
    } 

    GetImage is being called as a call back function

if i use following the value is retained

if (!Page.IsPostBack)
        {
            hdnVar.Value = "xyz";
        }

It takes value from above lines but is not updating it or inserting the value from the function, i.e, from postback 

0
pankajsachdeva
6/20/2008 8:43:16 AM
I haven't used the client callbacks in .Net, but I imagine that is the issue. The GetImage() method is returning a value you can access on the client, but any other changes such as updating hidden field values aren't actually reflected. You might have to concatenate the value you want in your hidden field to the current string you're returning from GetImage() and then parse it on the client to get the separate values out.

"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
6/20/2008 9:03:01 AM

I have found an alternate solution of doing it. It is working now. At least for now, though i am not sure about its feasibility. But some how i have managed to complete my task.

But i m still wondering if there is a proper solution for that??? 

Thanx anyways 


 

0
pankajsachdeva
6/20/2008 9:25:29 AM
Glad you got it working. Maybe you could post up your solution in case anyone else finding this thread can find it useful (and mark this thread as resolved). Thanks.

"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
6/20/2008 9:28:20 AM

I didnt found the proper solution i just saved the value in the hidden variable at the page load as it is not changing in the page. But if it change during the page execution i still dont know how to handle that

0
pankajsachdeva
6/20/2008 9:31:27 AM

since u r using the html control for hidden field so u can use this .........

alert('value '+document.getElementById('hdnVar').value);

 

no need to use this <%= hdnVar.ClientID %> this only us eto get the client id of .net control not for html control. 


With Regards,
Kaushik Choudhury
Software Engineer

"The future belongs to those who believe in the beauty of their dreams."
0
kaushik021
6/20/2008 11:08:11 AM

kaushik021:
alert('value '+document.getElementById('hdnVar').value);

The field does have the runat=server attribute so their use of the server-side ClientID is justified. Also, if you read the whole thread you'll see that it's moved on a little from the original question that was posted.


"Sometimes I think the surest sign that intelligent life exists elsewhere in the universe is that none of it has tried to contact us."
0
ramblor
6/20/2008 11:16:44 AM

It sounds to me like when you are clicking the button, it is causing the page to fire a postback event, in which case the value that you set inside the hiddenfield will probably be lost unless you allow it to retain its viewstate.

If you do <asp:HiddenField id="hdnVar" enableviewstate="true" runat="server">

It should retain its value during the postback.

Hope this helps,

James.


If this answered your question, please mark as an answer so others will know too.

http://wyerarch.blogspot.com
0
Wyerarch
6/20/2008 11:16:52 AM

ramblor:

The field does have the runat=server attribute so their use of the server-side ClientID is justified. Also, if you read the whole thread you'll see that it's moved on a little from the original question that was posted.

sorry i didnot notice the runat="server" tag.........

try to check whether ur that GetImage function is called or not.....


With Regards,
Kaushik Choudhury
Software Engineer

"The future belongs to those who believe in the beauty of their dreams."
0
kaushik021
6/20/2008 11:51:21 AM

 Hi james

        Yesterday i was busy but today morning first thing that i did was to try your suggestion. But it is still not working for me it is again getting null value. It is only work if i have following code written

if (!Page.IsPostBack)
        {
            hdn.Value = GetFileLength();
        }

 It is fullfilling my requirement but i m wondering what if i need to change that value during post back it is not saving that

i tried to use it in following way

if (Page.IsPostBack)
        {
            hdn.Value = GetFileLength();
        }

It gets correct value But it is still giving me null in the client side.

0
pankajsachdeva
6/21/2008 4:04:03 AM
Reply:

Similar Artilces:

Getting my client-side variable over to server-side
Ok so I have looked at a few posts on this subject and I can't quite figure out how to apply the idea to what I am doing here. I am using javascript to take amounts from 7 different textboxes and add them up on the fly, dropping the total in the 8th textbox. After they fill in that information they click button (postback) to continue throughout the form... what I need is for the "textboxTotalAmt" to move from client-side to server-side.  So I can access that total amount later in the form. Here is the Javascript piece... <script type="text/java...

How to get the Client side values in server side code.
Hi all, i have a proble i need to get the client side javascript values in C# code at server side. how can i pass those values? i am using version 1.1, i kno thatwe can use callback events mechnisam in 2.0 or ajax ,apart from that how we can pass? My problem is i need to stop the execution of the code based on after reciving values from the client   any ideas please???   Million thanks RamCheersRam MCP Hello Ram, a common approach is from javascript set an hidden field, then issue a postback. On the server-side, handle the post-back. Feel free to go deeper in your que...

Getting Value from Client-side InputBox to .net variable
hi, im doing a login page for our timekeeping. Since there's no msgbox available on asp.net, im doing it dynamically via javascript. How do i Get the value frm a dynamically written javascript (such as inputbox) to a .net variable? here's the logic of my program, user logs in hits the button and sub-routine Login will be fired, if user is late -- call Check_Late Sub, this is whre the client-side script was built -- then after that i wanted to be able to get the value from an inputbox. '// if button login clicked Sub Login(Sender As Object, E As EventArgs) .......

Hidden Field that is set on server side...not getting the last updated value from client?
Hi, I have a hidden field that tracks errors in my server side asp.net 2.0 code.  However, when I set the value to an error (from it's default value "NotSet") in the server side code and then when trying to access that Hidden Variable from the client the value is still set to the default value, "NotSet" instead of the error information. Any ideas as to what is going on here? Thanks in advance!   Server Side....  catch (Exception er) { Errors.Value = er.Message; o o o } Client Side.... function getErrors() { var cho = document.getElementById('<%=Errors.ClientID...

pls help: how to get client-side HTML "text field" value from a server side button
i copy some javascript from somewhere so user can choose pick up a date from a calendar and display the date onto a HTML text field. I have no knowledge in writing client side script(i.e. write code in html) can i write some code in a server-side button to get the value in the HTML text field??? i tried: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click textbox1.text = document.getElementById("htmltext").value End Sub but "document" is highlighted, and say isn't declar yet. and...

passing client side variable value to server side
 i have a grid and  by click on the rows, the onrowclick event is fired on client side. I want to pass the row index to the server side. As there are not sessions variables in javascript so i am stuck to pass the row to the server side.. I have made a texbox and set its valueto the index in the onrowclick event but when refresh calls, the text box became empty as the value set is on client side, i want page to persistthe value,  How can i do that? Tel me some way passing the row index to the server side?? Hi, You can call GridView_SelectedIndexChanging event on row click ev...

get server side datetime but run at client side
How do I get the server side datetime eg( 4 Aug 2006  6:12 : 01(seconds) AM  ) which the time is something similiar to ticking clock, once it get the server side datetime, it will pass to the javascript. From javascript it will increment the second by one, it is just similiar to ticking clock, after 10 seconds it will synchronize to the server datetime which means it get the latest server side datetime.   Is there any guide ? thanks in advance!!!kiwi_cyh Hi, It seems you want to synchronize the time in client side display with the server. You can use asynchronous clie...

How to get innerText from IFrame (on server-side / on client-side)
Hi, is there some posibility how to read inner text from IFRAME on server-side ?I've tested it with innerText and InnerHtml but it doesnt work I also tested it on client-side with JavaScript but I'm still not able to read innerText or innerHTML of that frame. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AJAX_Test.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title&...

Client side code to pass values to server side variable?
Hi there, I have ListBox_SelectedTextChanged() method that creates another list box in the runtime as follows: // Get Action Level List lbxActionLevel = new ListBox();lbxActionLevel.ID = "ddlA" + i.ToString(); lbxActionLevel.Width = 100; lbxActionLevel.Rows = 2;SqlDataReader dr = new BusinessLogicLayer().bllGetActionLevels(); lbxActionLevel.Items.Clear();while (dr.Read()) {ListItem lAction = new ListItem(); lAction.Text = dr.GetString(1).Trim();lAction.Value = Convert.ToString(dr.GetInt32(0)); lbxActionLevel.Items.Add(lAction); lbxActionLevel.SelectedIndex = 0; } I ...

I need to get a server side button to run this client side code?
I need to get a server side button to run this client side code when the server button is clicked and then subsequently called by the server. Is it possible? The problem is that the print control is a client side activex. I can call it normally using a client side button but this is no good when I need to print more then one page. Any help would be great. Thanks. The code: function PrintProc(){ var MyPrinter; MyPrinter = new ActiveXObject("ImgXPrint6.ImgXPrint"); MyPrinter.PageFrom = 1; MyPrinter.PageTo = 1; MyPrinter.PageM...

Setting the value of server side variable in javascript and wants to use that server side variable on page load.
Hi, I am trying to set the value of a server side variable in javascript and wants to use that variable on page load.  Here is my sample code. -------------------------- private string testVal = null;  private void registerScript(){ if (!this.Page.ClientScript.IsClientScriptBlockRegistered("RequestHeaderValidation")){ StringBuilder sb = new StringBuilder("" + Environment.NewLine);sb.Append(" var version = '2.0'; " + Environment.NewLine); sb.Append(" var isInstalled = Silverlight.isInstalled(version);" + Environment.NewLine)...

how can I get values of client side properties on the server
I define an img on the html like this:<img src=........  id=...   runat=server>I assign the value to src in javascript functions.My question: how do I get that src value on the server using c# or Vb.NetI tried this:  this.findcontrol(img.clientId)but what s next, how do I get the client side attributes like src, style properties and son on plsAnd vice versa, If I define server controls:  <asp:textbox id=myTextBox runat=server...>How do I access the properties of myTextBox  in javascript client side code so I can read them and eventually change themTh...

how do i get selectedValue of drop down list server side if i am populating it using client side javascript?
 Hi All.I am populating a drop down list client side using: The drop down list is populated based on a selection of another drop down list. ddlList.options[i] = new Option(1,2); as an exampleThe populating is done as i need it to. However, a button click event i am trying to get the selectedValue of the ddlList. However, it doesn't give me it. It only gives me the selectedValue of the drop down list on first rendering. Any ideas on how i can get it?   Could You paste some code? That would be helpful. Thanks S@ss (Shashi Shekhar Singh)My BlogPlease mark a post as ANSWER ...

Easy way to automatically update client-side equivalents of server-side hidden variables?
When changes are made to controls on an AJAX-enabled web form, I set this field to "true": <asp:HiddenField ID="needToSaveData" runat="server" />What I want to do is then have this HiddenField's value updated on the client-side too. To this end I found this article from Rick Strahl.  It looks like precisely what I need but then would force me to install his West Wind Ajax Toolkit.  Not a big obstacle but I got to wondering if there was a simple way to do the same thing with the basic Microsoft Ajax Controls and/or Control Toolkit?Robert W.&nb...

Web resources about - Getting hidden variable value from server side in client side - asp.net.getting-started

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

AD/CVD ruling and overseas capacity expansions are variables to the current PV boom, says EnergyTrend ...
China's National Reform and Development Commission has announced that there will be no significant reduction in feed-in tariff (FiT) rates for ...

Resources last updated: 12/18/2015 1:03:09 PM