Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit event of a submit type input isn't triggered

Tags:

javascript

I wrote a silly example to see which of the two, the click or the submit event, fires first on an input of type submit.

When I run it, though, nothing is written to the console.

Stepping through the code in the debugger reveals the following series of occurrences.

  1. It fires the click event handler first, writes the text "click" to the console, but then shortly afterwards, the text disappears from the console.

  2. Also, the submit event is never fired.

I infer that the form is getting submitted after executing the click event of the button. The thing I don't understand is why it isn't getting into my submit event handler?

Below is the relevant code, and here is the full working example. It's just a simple HTML file you can download and try out on your machine.

(function() {
let btn = document.getElementById("btnSave");

btn.addEventListener("click", function(event) {
	console.log("click");
}, false);
btn.addEventListener("submit", function(event) {
	console.log("submit");
	// event.preventDefault();
}, false);

console.log("All done now. Click da button, chum, click it I say!");

})();
div { margin: 20px; }
input[type="submit"] { width: 200px; height: 50px; }
<div>Look at the console and then click the button, chum!</div>

<div>
    <form>
        <input type="submit" id="btnSave" value="Save" width="200px" />
    </form>            
</div>
like image 404
Water Cooler v2 Avatar asked Dec 29 '18 07:12

Water Cooler v2


1 Answers

The thing I don't understand is why it isn't getting into my submit event handler?

input elements don't have a submit event. You need to hook submit on the form, not the input.

btn.form.addEventListener("submit", function(event) {
// ^^^^^
  console.log("submit");
  event.preventDefault();
}, false);

(btn.form there could be btn.closest("form") if you prefer, though btn.form is more widely-supported and is (also) standardized. Or, of course, use getElementById or querySelector to retrieve the form element.)

Live Example:

(function() {
  let btn = document.getElementById("btnSave");

  btn.addEventListener("click", function(event) {
    console.log("click");
  }, false);
  btn.form.addEventListener("submit", function(event) {
  // ^^^^^
    console.log("submit");
    event.preventDefault();
  }, false);

  console.log("All done now. Click da button, chum, click it I say!");

})();
div {
  margin: 20px;
}

input[type="submit"] {
  width: 200px;
  height: 50px;
}
<div>Look at the console and then click the button, chum!</div>

<div>
  <form>
    <input type="submit" id="btnSave" value="Save" width="200px" />
  </form>
</div>
like image 131
T.J. Crowder Avatar answered Sep 21 '22 11:09

T.J. Crowder