Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for "return value" from Javascript modal

OK, I'm by no means a JavaScript guru, and perhaps I'm still thinking in terms of Desktop software development, but this is what I'm trying to achieve :

  • I'm using Twitter Bootstrap's Modals
  • In some cases, before an action takes place, I want to verify it with a "Are you sure?" (Yes/No) Modal Dialog.

Question :

  • What should the inner logic be?

I mean :

  • User clicks buttonA (which ultimately performs actionA)
  • I want to launch the modal, wait for the input (either of the 2 buttons - yes/no) and/or pass it to some checking routine before performing(or not) actionA

This my HTML code for the modal (should the buttons be - somehow - acting via their onclick javascript routines?) - also note that #confirmMessage is going to be variable.

<div class="modal fade hide" id="confirmAlert">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">x</button>
        <h3 id="confirmTitle">Are you sure?</h3>
    </div>

    <div class="modal-body">
        <p id="confirmMessage">Body</p>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn" data-dismiss="modal">Cancel</a>
        <a href="#" class="btn btn-danger">Yes</a>
    </div>
</div>

Just an idea:

  • Write a function like checkBeforeExec(message,functionToExec)
  • Set #confirmMessage to message and Yes' href to javascript:functionToExec
  • Makes sense?

I know it may sound a bit confusing - but I simply do not know what the most javascript-friendly way to do this would be...

like image 898
Dr.Kameleon Avatar asked Aug 13 '12 09:08

Dr.Kameleon


2 Answers

I created a dialog manager around modal, with confirm helper function that does essentially this:

var callback = function(result) {
  alert(result);
}); // define your callback somewhere

$('#confirmAlert').on('click', '.btn, .close', function() {
  $(this).addClass('modal-result'); // mark which button was clicked
}).on('hidden', function() {
  var result = $(this).find('.modal-result').filter('.btn-danger').length > 0; // attempt to filter by what you consider the "YES" button; if it was clicked, result should be true.

  callback(result); // invoke the callback with result
});

Also, you should make both the Cancel and Yes button data-dismiss="modal".

Here's a fiddle, with a simple example of my dialog manager.

Note, that if you are using Bootstrap 3, you should add a handler to the hidden.bs.modal event instead of hidden.

like image 102
moribvndvs Avatar answered Nov 15 '22 14:11

moribvndvs


With jquery you can use something like

$('.btn').click(function(){
   val=$(this).val()
   if(val=='Yes'){
     //continue the processing
   }
})
like image 1
Nick Avatar answered Nov 15 '22 13:11

Nick