user3195396
user3195396

Reputation: 254

How do I call a jquery code from code behind?

Right now i'm hiding div elements with this script

$(document).ready(function () { 

            $('#<%=phaseOne.ClientID%>').hide();
            $('#<%=phaseTwo.ClientID%>').hide();
            $('#<%=phaseThree.ClientID%>').hide();
});

And I wanted it to show with a $('#<%=phaseOne.ClientID%>').show(); code for an example upon triggering a button that is base on a logic and status from the database

Upvotes: 0

Views: 1423

Answers (3)

SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6056

Try following:

<script type="text/javascript">
$(document).ready(function () { 
   HideAll();
}
 function HideAll() 
{   
  $('#<%=phaseOne.ClientID%>').hide();
  $('#<%=phaseTwo.ClientID%>').hide();
  $('#<%=phaseThree.ClientID%>').hide();
}

function ShowPhase1()
{
  $('#<%=phaseOne.ClientID%>').show();
}

</script> 
  • Use GetType() instead of typeof(Page) in order to bind the script to your actual page class instead of the base class

  • Pass a key constant instead of Page.UniqueID, which is not that meaningful since it's supposed to be used by named controls,

  • End your Javascript statement with a semicolon

In Code Behind on Button Click:

if(somecondition==true)
{
  ScriptManager.RegisterStartupScript(this, GetType(), "key", "ShowPhase1();", true);
}

Add as much as function to show/hide and call from codebehind.

Upvotes: 1

Ted
Ted

Reputation: 4057

Change your code to the following:

$(document).ready(function () { <% if (someservervalue == true) { %> $('#<%=phaseOne.ClientID%>').show(); <% } else { %> $('#<%=phaseOne.ClientID%>').hide(); <% } %> $('#<%=phaseTwo.ClientID%>').hide(); $('#<%=phaseThree.ClientID%>').hide(); });

Another way would be to use Page.RegisterClientScriptBlock. More info: http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock(v=vs.110).aspx

Upvotes: 0

Vikram
Vikram

Reputation: 1627

you can call the javascript fucntion as shown below

in the C# code you can call the following code on completion of condition

ScriptManager.RegisterStartupScript(this, Page.GetType(), "key", "Display()", true);

and in the .aspx page you can have your div and function mentioned as below

<script type="text/javascript">
 function Display() {            
            var e = document.getElementById('<%=phaseOne.ClientID%>');         
            if (e.style.display == 'block')
                e.style.display = 'none';
            else
                e.style.display = 'block';
            return false;
        }
 </script>

<div id="phaseOne" style="display: none;position:absolute;  
    top:300px;
    right:250px;  "</div>

Upvotes: 3

Related Questions