Search code examples
javascriptjqueryhtmlformsbootbox

Prevent button submissions with bootbox confirm and display their values on message


I have a simple form with 3 buttons, each doing a different action. On one's click I want the user to confirm his action using bootbox.confirm(). I want the confirmation box to display: "Are you sure for your choice:" + value. How can I achieve this?

HTML:

<form action="" method="post">
     <button  type="submit" name="action" value="success" class="confirm"></button>
     <button type="submit" name="action" value="fail" class="confirm"></button>
     <button type="submit" name="action" value="no exam" class="confirm</button>
</form>

Javascript / jquery I tried:

<script>
  $(document).ready(function() {
    $(document).on("click", ".confirm", function(e) {
        e.preventDefault();
        bootbox.confirm("Are you sure for your choice?", function(result) {
        if (result) {
          console.log("user confirmed");
        } else {
            console.log("user declined");
        }
      });
    });
  });
</script>

Is this the right way (with classes on every button) or I have to select the form? I get the confirm box and the logs correctly, but on success i don't know how to submit. Also I don't know how to put the chosen value in the message.


Solution

  • Hopefully you've been able to figure this out, but if not here is all you were missing. Also, because this flow is async, don't move the e.preventDefault() to the callback.

    $(document).ready(function() {
        $(document).on("click", ".confirm", function(e) {
            e.preventDefault();
            var $this = $(this);
            bootbox.confirm("Are you sure for your choice: "+$this.val()+"?", function(result) {
                if (result) {
                    console.log("user confirmed");
                } else {
                    console.log("user declined");
                }
            });
        });
    });