1
votes

I've been looking for a method of adding a jQuery event to a button which once clicked will fire the event followed by the asp postback.

Adding the event is easy enough the issue however is delaying the asp postback temporarily.

Asp Code (Events added in C#):

<input runat="server" ClientIDMode="static "id="cancelButton">

JQuery Code:

var cancelBtn = jQuery('#cancelButton');

cancelBtn.click(function (e) {
    e.preventDefault();

    var cancelBtnEvent = cancelBtn[0].click;

    jQuery(pnl).animate({
        height: 200
    }, 300, 'swing', function () {
        cancelBtnEvent();
    });
}); 

In the code above I am adding a click event to the button, 'cancelBtn' is an input[type="button"]. The event will stop the defaults, save the click function to call later, do some animation then call the click function. However this fails with the error invalid object call.

So my question:

How should this be done? or Can my solution be fixed?

Thanks

3
Is 'cancelBtn' an anchor tag <a>? - A. Wolff
Apologises should have that clear, will update question. - PinkSFer
Please explain reasoning behind downvote? - PinkSFer

3 Answers

1
votes

EDIT 1

Here is a simple trick that would work for you. Sorry, I didn't noticed the question before, carefully.

var IsFirstLoad = true;// Declare globally (outside ready function)
        cancelBtn.click(function (e) {
            if (IsFirstLoad) {
                e.preventDefault();
            }
            jQuery(pnl).animate({
                height: 200
            }, 300, 'swing', function () {
                jQuery('#cancelButton').click();
                IsFirstLoad=false;
            });
        });

Answer posted first.(won't work in this scenerio). Sorry!

jQuery(pnl).animate({
        height: 200
    }, 300, 'swing', function () {
        jQuery(cancelBtn).click();
    });

Try using jQuery(cancelBtn).click(); instead of cancelBtnEvent();. If cancelBtn is a jQuery element simply cancelBtn.click() would be enough.

0
votes

First of all are you sure that your selector cancelBtn is correct? ASP.net modifies asp elements ids, so that you cannot address them by $("MyElementId") any more. Instead you will have to use e.g. $("[ID$=MyElementId]"). So what kind of object is cancelBtn?

Why do you save the click event in a variable? Instead you could call it directly:

jQuery(pnl).animate({
    height: 200
}, 300, 'swing', function () {
    jQuery(cancelBtn).click();
});

Note that you do not need to get the DOM element by using cancelBtn[0].

0
votes

this is also possible:

jQuery(cancelBtn).trigger("click");