Q:

HTML5 dialog element close button not working properly

I'm looking at this question post, and I'm having trouble applying it to work in my code.
It's confusing me because I'm doing the exact same thing for the save button as I am the cancel button (at least, the part about it closing) and nothing happens upon clicking cancel.
<dialog class="my-modal"> 
                <p>Add Cust</p>
                <label for="nameField">Name</label><input id=nameField><br>
                <label for="addressField">Address</label><input id=addressField><br>
                <label for="cityField">City</label><input id=cityField><br>
                <label for="stateField">State</label><input id=stateField size=2> &nbsp;
                <label for="zipField">Zip</label><input id=zipField><br>

                <br>
                <button onclick="closeAndSave()">Save</button>
                <button onclick="close()">cancel</button>
            </dialog>

function close(){
    const modal = document.querySelector('.my-modal');
    modal.close();
}

Have also tried:
<button class="btn btn-default" data-dismiss="my-modal" aria-label="Close">Cancel</button>

A:

Another way to approach this would be to bind behavior to buttons in your script, rather than to specify functionality for buttons with the inline "onclick" attribute. 
The "inline onclick method" can lead to unexpected behavior (which may be the cause of the problem in your case). An example would be, if close() is redefined/reassigned elsewhere in your apps global scope, then that would cause "the wrong close function" to be called by the dialog's close button.
Consider revising your HTML and script so that event binding is delegated to your script for better control, as shown below:

/* Obtain modal as before */
const modal = document.querySelector('.my-modal')

/* Select buttons from modal and bind click behavior */
modal.querySelector("button.cancel").addEventListener("click", () => {
  /* Call close method on modal to dismiss */
  modal.close();
});

modal.querySelector("button.save").addEventListener("click", () => {
  alert("save data");
  modal.close();
});

/* Added for snippet to prelaunch dialog */
modal.showModal();
<dialog class="my-modal">
  <p>Add Cust</p>
  <label for="nameField">Name</label><input id=nameField><br>
  <label for="addressField">Address</label><input id=addressField><br>
  <label for="cityField">City</label><input id=cityField><br>
  <label for="stateField">State</label><input id=stateField size=2> &nbsp;
  <label for="zipField">Zip</label><input id=zipField><br>
  <br>
  <!-- Replace onclick with classes to identify/access each button -->
  <button class="save">Save</button>
  <button class="cancel">cancel</button>
</dialog>

Hope that helps!

