Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a jQuery function from code-behind?

I am trying to call a jQuery function from ASP.NET code behind.

I don't want it to be triggered by the jQuery click event; I want to trigger the jQuery function--->"show the dialog" in the code behind of my control.

$(document).ready(function () {
    $("#LinkButton1").click(function(){
        $("#hightlight_show1").toggle();
    });

    var dialog1 = $("#Add").dialog({
            autoOpen: false,
            width: 620,
            height: 400
    });

    // Move the dialog back into the <form> element 
    dialog1.parent().appendTo(jQuery("form:first"));

    $("#BT_add").click(function () {
       $("#Add").dialog("open");
       return false;
});

I have tried something like this but it did not work:

$(document).ready(function () {
    $("#LinkButton1").click(function () {
        $("#hightlight_show1").toggle();
    });

    var dialog1 = $("#Add").dialog({
        autoOpen: false,
        width: 620,
        height: 400
    });

    // Move the dialog back into the <form> element 
    dialog1.parent().appendTo(jQuery("form:first"));

    function a() {
        $("#Add").dialog("open");
        return false;
    };

});

I specify this in the code behind using Page.ClientScript.RegisterStartupScript():

Page.ClientScript.RegisterStartupScript(
    this.GetType(),
    "a",
    "a();",
    true
 );
like image 214
zzz Avatar asked Oct 03 '22 12:10

zzz


2 Answers

First, move your function a() { out of the $(document).ready().

But you might still have an issue with order of execution.

If this is a full postback, then wrap the a() call in your RegisterStartupScript with another $(document).ready(). If it's a partial postback from an UpdatePanel, it should work as long as the dialog was properly created the first time the page loaded.

like image 118
Jason P Avatar answered Oct 12 '22 11:10

Jason P


You can not trigger JavaScript function from code behind. You can define JavaScript function on html page and bind the click event on server side using Control.Attributes.Add. You will need server control to bind the event, you can make html control server accessible by put runat="server"

Javascript

function  YourFun(){
    $("#hightlight_show1").toggle();
}

Code behind

hightlight_show1.Attributes.Add("onclick", "YourFun();");
like image 43
Adil Avatar answered Oct 12 '22 12:10

Adil