John Doe
John Doe

Reputation: 3233

Understanding how to use callback

I am still new to javascript and Jquery. I understand that javascript will execute each line as it encounters it. So in the case (when my value > 9)

What I would like to happen is for the custom alert to fire off, and once the alert is closed then have the window.open execute.

How can I accomplish this?

if ($('#MyCount').val() > 9) {
            MyCustom.alert("MyTitle", " Some text.... ");
            window.open(url, 'Print', "toolbar=no,menubar=no,status=no");
}else {
      window.open(url, 'Print', "toolbar=no,menubar=no,status=no");
}

Upvotes: 2

Views: 82

Answers (2)

Mark C.
Mark C.

Reputation: 6450

I just put this example together for you.. I hope it makes sense.

We basically pass the callback function as the third parameter to MyCustom.alert, and listen for the 'dialogclose event from jQuery UI.

HTML

<input id="MyCount" type="text" />
<input type="button" id="test" />

<div id="someAlert">
    <h1></h1>
    <p></p>
</div>

JavaScript

var MyCustom = {};

MyCustom.alert = function(p1, p2, callback) {
    $("#someAlert").dialog();
    $("#someAlert").children("h1").text(p1);
    $("#someAlert").children("p").text(p2);

    alert(typeof(callback));

    $("#someAlert").on('dialogclose', function(){
        callback();
    });
};

function doSomething(){
 alert("I'm the callback");   
}

var greaterThan9 = function () { 
    if ($('#MyCount').val() > 9) {
                MyCustom.alert("MyTitle", " Some text.... ", doSomething);
                //window.open(url, 'Print', "toolbar=no,menubar=no,status=no");
    } else {
    }
}

$("#test").on("click", function(){
   greaterThan9(); 
});

Upvotes: 0

Igor
Igor

Reputation: 15893

if ($('#MyCount').val() > 9) {

change to

var myCount = parseInt($('#MyCount').val());
if (!isNaN(myCount) && myCount > 9) {

The rest depends on the implementation of MyCustom.alert. If it is a wrapper for javascript native alert, then your code will work as is. If it is using an html dialog, you need to pass it a callback to run when it closes.

Upvotes: 1

Related Questions