Search code examples
javascriptformspromptalertify

How to wait until one function completes and loops


This is part of my code :

document.querySelector("#edit_<?= $row["item_id"]; ?>").addEventListener("submit", function(a){
    if(!completed){
        a.preventDefault();
    }else{
        return true;
    }

    if((function(){
        alertify.prompt("New Amount of Item : ", function(e, str){
            if(e){
                document.querySelector("#edit_<?= $row["item_id"]; ?> input[name=\"item_amount\"]").value = str;
                var completed = true;
                return true;
            }else{
                return false;
            }
        })
    )() == true){
        document.querySelector("#edit_<?= $row["item_id"]; ?>").submit();
    }
});

Where <? $row["item_id"]; ?> will return something (ignore it, it isn't the real problem)

But the problem is that I need to wait until alertify.prompt() gets str and then put it to

document.querySelector("#edit_<?= $row["item_id"]; ?> input[name=\"item_amount\"")

(Sorry for this messy code)

What can I do to solve this?

P.S. Better not use a jQuery solution if possible because it is already given. Use a Javascript-Only solution please.


Solution

  • Remove the second if condition and just use the alertify callback function:

    // define the completed variable outside the callbacks
    var completed = false;
    document.querySelector("#edit_<?= $row["item_id"]; ?>").addEventListener("submit", function(a){
        if(!completed){
            a.preventDefault();
        }else{
            return true;
        }
        alertify.prompt("New Amount of Item : ", function(e, str){
            if(e){
                document.querySelector("#edit_<?= $row["item_id"]; ?> input[name=\"item_amount\"]").value = str;
                //no var before completed, because then it would be local to this callback function
                completed = true;
                // here instead returning "true" do what you wanted to do if true
                document.querySelector("#edit_<?= $row["item_id"]; ?>").submit();
            }
        });
    });