Return result in place of false in javascript function

85 Views Asked by At

I want to return the result in place of false.Please help me out, already tried using window object and putting it in a variable then accessing.

$(document).ready(function() {
  $('#confirm').on('click', function() {
    bootbox.confirm("Are You Sure ?", function(result) {
      bootbox.alert("Confirm result: " + result)
    });
    return false;
  });
});
3

There are 3 best solutions below

0
On

bootbox.confirm is an async operation, unlike window.confirm which stops Javascript execution until the user makes a choice. So if you intend to do some operation once user confirms or cancels, you can do it in the callback function. But you can't return it as a value. You could do something like this:

function userHasConfirmed() {
  console.log("yay!");
}

$(document).ready(function() {
  $('#confirm').on('click', function() {
    bootbox.confirm("Are You Sure ?", function(result) {
      // The code here is executed only after the user makes a choice.
      bootbox.alert("Confirm result: " + result)
      if (result) {
        userHasConfirmed();
      }
    });

    // The code here does not wait for the user to make a choice.
    console.log("Asked the user to make a choice, but they may or may not have made a choice yet!");
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>

<div id="confirm">Click me!</div>

0
On

You are using a anonymous function as a callback in a event listener if you want to do something with result you can do in this function or another approach would be to pass a function as a parameter to the on "click" event register that will be called on click.

$(document).ready(function() {

   onClickCallback(e){ 
      //do something here 
   }

   $('#confirm').on('click', onClickCallback);
});
0
On

Thanks guys i figured this out.Code above is working like this

 $(document).ready(function () {
        $('#confirm').on('click', function () {
            bootbox.confirm("Are You Sure ?", function (result) {
                if(result == true){
                    window.location.href = $('#confirm').attr('href');
                } 
            });
            return false;
        }); 
    });