简体   繁体   中英

Populate hidden div and when it's done show the div

So I have this issue : in a form I have this button. When I click on it, I want 2 things to happen :

  1. Populate fields in a hidden div by using $.getJSON(url)
  2. And when it's done, to show the div

Except that everytime, the div is shown before the fields value are set and thus you can see the value being changed.

Here's what I tried :

var promise = $.getJSON(url);
var done = promise.done(function(data){
    //setting the value for the fields in the hidden div
});
if (done){
    showHide(id); //show the div
}

FYI, showHide(id) is a function defined in an external Javascript file whereas the rest of the code is defined inside a script tag in a jsp file (I obviously included the Javascript file).

I also tried putting the showHide function inside the anonymous function but in that case, showHide is not called at all (as if it wasn't recognized).

What is it that I can do ? Thanks in advance

You could use a Promise to achieve that.

Do whatever you want inside a new Promise . resolve it when you're done then do the next things in a .then()

 var promise = new Promise((resolve, reject) => { //I'll use a setTimeout here to demonstrate setTimeout(function(){ $('#toShow').text('I\\'m done here !'); resolve(); },2000); }); promise.then(function(){ console.log($('#toShow').text()); }); 
 div{ display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="toShow"></div> 

You could use success and error callback functions, as described in the jQuery documentation :

$.getJSON(url, function(result) {
    // Success
    $("#myDiv").text(result);
    $("#myDiv").show();
})
.error(function() { 
    // Fail
    alert("error"); 
})

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