1

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>
4
  • 1
    if ( true ) { $('.button2).click() } Commented Aug 12, 2016 at 18:23
  • 2
    @u_mulder: That way lies unmaintainable spaghetti. :-) Commented Aug 12, 2016 at 18:25
  • 2
    How about just another named function, that can be called from both event handlers? Commented Aug 12, 2016 at 18:26
  • why do you need to register 2 click events for the same button? can't you just resolve it all in one function? Commented Aug 12, 2016 at 18:32

1 Answer 1

5

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...*/);
  });
})();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.