confirm form submit with jquery UI

前端 未结 1 499
挽巷
挽巷 2020-12-04 01:06

I\'m trying to confirm a submit form that is created using ruby on rails, but before submitting I have a condition that open a confirm popup asking if the user really wants

相关标签:
1条回答
  • 2020-12-04 01:42

    The issue is in the way that the browser handles it's own alert, confirm, and prompt versus self generated dialogs. You need to add in a try/catch sort of scenario.

    I created the following a bit back to address this: https://jsfiddle.net/Twisty/7kp46r22/3/

    This uses $.Deferred and $when() to wait for the user to make a selection before returning the results or executing any callbacks.

    For your application, this might look like:

    Working example: https://jsfiddle.net/Twisty/wtogu9cu/

    HTML

    <form id="myForm">
      Submit Form:
      <button type="submit">Go</button>
    </form>
    

    jQuery

    function ui_confirm(message, callback) {
      var dfd = $.Deferred();
      var dialog = $("<div>", {
          id: "confirm"
        })
        .html(message)
        .appendTo($("body"))
        .data("selection", false)
        .dialog({
          autoOpen: false,
          resizable: false,
          title: 'Confirm',
          zIndex: 99999999,
          modal: true,
          buttons: [{
            text: "Yes",
            click: function() {
              $(this).dialog("close");
              dfd.resolve(true);
              if ($.isFunction(callback)) {
                callback.apply();
              }
            }
          }, {
            text: "No",
            click: function() {
              $(this).dialog("close");
              dfd.resolve(false);
            }
          }],
          close: function(event, ui) {
            $('#confirm').remove();
          }
        });
      dialog.dialog("open");
      return dfd.promise();
    }
    $(function() {
      $('#myForm').submit(function(e) {
        e.preventDefault();
    
        // your code
    
        $.when(ui_confirm("Are you sure?")).done(function(val) {
          if (val) {
            console.log("Submit the form.");
            $('#myForm')[0].submit();
          } else {
            console.log("Do not submit the form.");
          }
        });
      });
    });
    
    0 讨论(0)
提交回复
热议问题