简体   繁体   中英

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

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>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM