Reputation: 355
Is it possible to trigger my confirm condition to other function?
myphp.php
<input type="button" id="button1" class"button2">
<script>
$('#button1').on('click', function(){
if(confirm("Are you sure?")){
//my stuff
}else{
return false;
}
});
$('.button2).on('click', function(){
//if the confirm condition from first function return true
//i need to fire here as well without doing another if(confirm)
});
</script>
Upvotes: 1
Views: 251
Reputation: 1074138
I would suggest you modularize your code by putting the logic you want to use in two places in a function that both places can call:
// The function doing the thing
function doTheThing(/*...receive arguments here if needed...*/) {
// ...
}
$('#button1').on('click', function(){
if(confirm("Are you sure?")){
doTheThing(/*...pass arguments here if needed...*/);
}else{
return false;
}
});
$('.button2').on('click', function(){
//if the confirm condition from first function return true
//i need to fire here as well without doing another if(confirm)
doTheThing(/*...pass arguments here if needed...*/);
});
Side note: I've shown it at the top level of your script, but if you haven't already (and you haven't in your question), I would suggest putting all of your code in an immediately-invoked scoping function in order to avoid globals:
(function() {
// The function doing the thing
function doTheThing(/*...receive arguments here if needed...*/) {
// ...
}
$('#button1').on('click', function(){
if(confirm("Are you sure?")){
doTheThing(/*...pass arguments here if needed...*/);
}else{
return false;
}
});
$('.button2').on('click', function(){
//if the confirm condition from first function return true
//i need to fire here as well without doing another if(confirm)
doTheThing(/*...pass arguments here if needed...*/);
});
})();
Upvotes: 5