Skip to content Skip to sidebar Skip to footer

Use Asp:hiddenfield Value In Javascript On Page Load?

I'm trying to use the value of an asp:HiddenField control in javascript after postback and pageload.I tried something like this but it does not work.(the get function works fine bu

Solution 1:

You should get the hidField value inside the Get function, you have also type coersion problems, since the 'value' property of the input is a string, and you are incrementing directly it without converting it first to number:

functionGet(checbox) {   
  var hidField = document.getElementById("<%=hidField.ClientID %>"),//get element
      hidVal = +hidField.value || 0; // get the value and convert it to number,// set 0 if conversion failsif(checbox.checked) {
    hidVal++; 
  } else {
    hidVal--;
  }
  hidField.value = hidVal; // set the value back
}

Solution 2:

remember to put the javascript part before the closing tag so when it get's there, the HiddenField is already rendered and can usable.

and, for CMS answer, do not forget to use:

<asp:CheckBoxID="chk"runat="server"onclick="Get();" />

Solution 3:

As I understood I have written the following code. please review.

<scripttype="text/javascript"language="javascript">functionGet(checbox)
    {
    var hidVal;
    if(document.getElementById("<% =hidField.ClientID %>").value!="")
    {
    hidVal=parseInt(document.getElementById("<% =hidField.ClientID %>").value);
    }
    else 
    hidVal=0;

      if(checbox.checked)hidVal += 1;
            else hidVal -= 1;
            alert(hidVal);
      document.getElementById("<% =hidField.ClientID %>").value = hidVal.toString();

    }

Now I have added the following code in my aspx page:

<div><asp:CheckBoxID="chk1"Text="1"runat="server"onclick="javascript:Get(this);" /><asp:CheckBoxID="chk2"Text="2"runat="server"onclick="javascript:Get(this);" /><asp:CheckBoxID="chk3"Text="3"runat="server"onclick="javascript:Get(this);" /><asp:CheckBoxID="chk4"Text="4"runat="server"onclick="javascript:Get(this);" /><asp:CheckBoxID="chk5"Text="5"runat="server"onclick="javascript:Get(this);" /><asp:HiddenFieldID="hidField"runat="server" /><asp:ButtonID="btnSubmit"runat="server"Text="Create"OnClick="btnSubmit_Click" /><hr/><asp:LabelID="lblHidValue"runat="server"></asp:Label></div>

Now in aspx.cs page_load contains the following:

lblHidValue.Text ="In page_load "+ hidField.Value;

and the button click event as follows:

protectedvoidbtnSubmit_Click(object sender, EventArgs e)
    {
        lblHidValue.Text += "<br/>In button click " + hidField.Value;

    }

Please check if these can solve your problem.

Post a Comment for "Use Asp:hiddenfield Value In Javascript On Page Load?"