user2087008
user2087008

Reputation:

Javascript Button OnClick Callback

I'm trying to emulate the confirm() functionality with my own styled modal. I have a function with a callback:

function confirmChanges(callback) {

    function clickOkay() {
        callback(true);
    }

    function clickCancel() {
        callback(false);
    }
}

This section is where I need the confirmChanges function to return true/false:

if (unsavedChanges == true) {
    j$('.confirm').showModal();
    if (confirmChanges(function(result) {return result;})) 
    {
        // Do stuff and return true
    } 
    else 
    {
        return false;
    }
}

Here's my HTML I'm using for the modal:

<div class="warningpop confirm">

    <h3>Unsaved Changes!</h3>                         
    <a id="modalContinue" value="Continue" onclick="clickOkay();"/>  
    <a id="modalCancel" value="Cancel" onclick="clickCancel();"/>   

</div>

However when I click the buttons in the dialog I get the error "clickCancel() / clickOkay() is not defined".

How can I fix it so that it returns true or false depending on the button clicked?

Upvotes: 1

Views: 26857

Answers (1)

Shubham
Shubham

Reputation: 1793

Is this what you want or i got you wrong? Please feel free to query.

function getResponse(res, func) {
  
  if(res) {
    console.log(1);
    //do something
  } else {
    console.log(2);
    //do otherthing
  }
  
  /* If tou want to call some other function dynamically. */
  
  func();
}

function one() {
  console.log("calling function one");
}

function two() {
  console.log("calling function two");
}
<div class="warningpop confirm">

    <h3>Unsaved Changes!</h3>                         
    <a id="modalContinue" value="Continue" onclick="getResponse(true, one);">Yes </a>  
    <a id="modalCancel" value="Cancel" onclick="getResponse(false, two);">No </a>

</div>

Upvotes: 2

Related Questions