15

I need to run a javascript function from ASP.NET code behind AFTER the page is completed.

I've used this code so far but it returns "undefined" because the hidden field is not filled with the value when javascript function is fired.

What should I do? Thanx in advance.

ASPX:

  <asp:HiddenField runat="server" ID="ColorHiddenField" ClientIDMode="Static" Value="0" />

Javascript:

    function HandleColors() {
        alert($('#<%= ColorHiddenField.ClientID %>').val());
    }

Code Behind:

  ColorHiddenField.Value = item.Color;
  ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "HandleColors();", true);
Payam Sh
  • 531
  • 4
  • 8
  • 21
  • Check out the answers here for a few options: http://stackoverflow.com/questions/799981/document-ready-equivalent-without-jquery – Prescott Nov 29 '14 at 21:05

3 Answers3

31

try code below, it uses jQuery document.ready to run your script after page loads:

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { HandleColors(); });", true);
Mohamad Shiralizadeh
  • 7,153
  • 5
  • 52
  • 78
4

use RegisterStartupScript instead of RegisterClientScriptBlock like

ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "HandleColors();", true);
TouchStarDev
  • 345
  • 1
  • 7
  • 15
2

try with jquery document ready.

$( document ).ready(function() {
   alert($('#<%= ColorHiddenField.ClientID %>').val());
});