skip to Main Content

When button is clicked, click events bubble up to form and execute the proper callbacks. However, after the button is deleted, formSubmitCallback isn’t triggered which theoretically should be, due to the submit event. I can’t find exactly why this happens. Is the submit event called somehow after the DOM is updated? I’m not looking for a solution to this, but rather an explanation for the behavior.

HTML:

<form onsubmit="formSubmitCallback()" onclick="formClickCallback()">
  <div onclick="divCallback()">
    <button id="button" onclick="buttonCallback()">
      click me
    </button>
  </div>
</form>

JS:

function buttonCallback() {
  console.log("button")
  document.getElementById("button").remove()
}

function divCallback() {
  console.log("div")
}

function formClickCallback() {
console.log("form click")
}

function formSubmitCallback() {
  console.log("form submit")
}

Result:

"button"
"div"
"form click"

2

Answers


  1. I think you need to do

    <input type="submit" id="button" onClick="buttonCallBack()">
    click me
    </input>
    

    instead of

    <button  id="button" onClick="buttonCallBack()">
    click me
    </button>
    

    so that the form knows that the button is supposed to submit the it.

    Login or Signup to reply.
  2. A quick google reveals that: "a div usually needs at least a non-breaking space ( ) in order to have a width".

    So I guess because your div doesn’t have that, it takes up 0 pixels, thus can’t be clicked on the screen

    If you just add any text in the div, then the second and third callbacks will fire again:

    <form onsubmit="formSubmitCallback()"
    onclick="formClickCallback()">
      <div onclick="divCallback()">
        sometext
        <button id="button" onclick="buttonCallback()">
          click me
        </button>
      </div>
    </form>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search