Steven Zhou
Steven Zhou

Reputation: 78

How to detect the mouse click from browser triggered by Enter key press?

I notice that on modern browsers such as Chrome, when placing one text field and one button within a form element. If enter key is pressed from the text field, the button will get clicked with a mouse click event issued by browser.

Since the only button within the form isn't used for submitting the form, is there a way for that button to only accept user click instead of browser click?

<form action="javascript:void(0)">
  <input type="text"/>
  <button id="btn">Submit</button>
</form>
var btn = document.getElementById("btn");
btn.onclick = function() {
  alert("button clicked");
}

https://codepen.io/stevenz1987/pen/poEBmqv

Upvotes: 1

Views: 543

Answers (2)

FZs
FZs

Reputation: 18619

That doesn't happen because it's the only button in the form, but rather because it's a submit button.

<button> elements default to type="submit" when associated with a form.

To disable that behavior, set the type attribute to button manually:

<button id="btn" type="button">Submit</button>

Try it on CodePen

Upvotes: 1

Amit Saini
Amit Saini

Reputation: 595

You need to assign the "type" attribute to the "button" element. Like below:

var btn = document.getElementById("btn");
btn.onclick = function(e) {
  e.preventDefault();
  debugger;
  alert(123);
}
<form action="javascript:void(0)">
  <input type="text"/>
<button type="button" id="btn">Submit</button>
  </form>

Upvotes: 1

Related Questions