Javascript - waiting for a click before ending function
I have made what is essentially a lightbox whereby if a change requires the user to confirm their password, this lightbox pops up and the user enters there password etc.
I am triggering the function like this:
if(verifyPassword())
{
//apply change
}
The verify function is:
function verifyPassword() {
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error)
{
if开发者_StackOverflow中文版(check.password)
{
//show password error
return false;
}
else
{
//show error
return false;
}
}
else
{
return true;
}
}, 'json');
});
}
Basically I am needing the function to wait until #submit
is clicked to return either true or false.
Thanks in advance
Since jQuery 1.5.0
, you can do apply some magic with Deferred objects
:
$.when( verifyPassword() ).done(function() {
// do something
});
You would need to re-write verifyPassword()
a little:
function verifyPassword() {
var Notify = $.Deferred();
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error) {
if(check.password) {
//show password error
Notify.resolve();
}
else {
//show error
Notify.reject();
}
}
else {
return true;
}
}, 'json');
});
return Notify.promise();
}
This might not be the most elegant way of achieving your goal here, I'm just saying you could do it in a way like this :-)
Don't stall, instead provide a callback:
function verifyPassword(f) {
/**
* Do all your logic here, then callback to the passed function
*/
f(result);
}
verifyPassword(function (correct) {
if (correct) {
/* Continue */
}
else { /* Other */ }
});
I think you want to convert your $.post()
call into the more generic $.ajax()
jQuery call, and pass in async: false
. Something like:
$.ajax('', { async:false, data: {password:...}, success: function() {
// ... success callback ...
}});
精彩评论