简体   繁体   中英

jQueryUI Modal Refreshing Page on Close

In my jQueryUI modal, whenever I click on the buttons, the parent page refreshes, even when I have preventDefault() or return false . Is this expected behavior?

The HTML:

<li><a id="addFunds" class="no-close" href="#">Add Funds</a></li>

The modal:

<div id="addFundsModal" class="modal-hidden" title="Add Funds to Your Account">
    <div class="leftBar">
        <h3>Add Funds</h3>
                //other stuff
                <form>
                      //<fieldset>, etc.
                      <button class="modal-close btnBlue" href="#">Cancel</button>
              <button class="add-funds btnGreen">Add Funds</button>
        </form>
    </div>
</div>

The jQuery:

$('#loggedInDropdown').on('click', '#addFunds', function(e) {
        e.preventDefault();
        $('#addFundsModal').dialog({
            modal: true,
            dialogClass: 'no-close',
            width: 500
        });
    });

    $('.ui-dialog').on('click', '.modal-close', function(e) {
        e.preventDefault();
        $('#addFundsModal').dialog('close');
    });

I'm also not sure about whether I should use dialog.close or dialog.destroy , but that is for another post, I suppose.

We usually attach the button behavior inside the .dialog options:

.dialog({
      resizable: false,
      height:240,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $( this ).dialog( "close" );
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });

Your issue is in the event delegation, i think your click event for cancel never gets executed because .ui-dialog is created only the first time you click on the link so initially attaching the event to that class doesn't take any effect (as .ui-dialog doesn't exist then) and with normal button behavior form submits, page refreshes.

Try:

$('#addFundsModal').on('click', '.modal-close', function (e) {
    e.preventDefault();
    $('#addFundsModal').dialog('close');
});

or apply it to the class (must better)

$('.modal-hidden').on('click', '.modal-close', function (e) {
    e.preventDefault();
    $('#addFundsModal').dialog('close');
});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM