My junior and I were debugging an issue on a web page where pressing the enter key while entering text in an input field triggers a button. Let's call that button 'Button B'.
We didn't know why this was happening. There are two buttons, A and B, on that page, but only Button B's `onclick` is triggered.
Upon closer inspection:
Button A code:
<button type="button" name="sample" class="green-button">Button A</button>
Button B code:
<button name="sample2" class="green-button">Button B</button>
The `type` attribute is missing in Button B. After we added the `type`, Button B was no longer triggered by the enter key.
Okay, cool! What is the default `type` attribute for a button?
When we explored the MDN docs, we found that the default button type is `submit`, which caused this issue.
Proof of Concept:
- Keep the cursor in the input text field and press enter; the submit button's `onclick` will be called.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form with Buttons</title> </head> <body> <h1>Sample Form</h1> <form id="myForm"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <br><br> <button type="button" onclick="alert('Button with type button clicked!')">Button Type None</button> <button type="submit" onclick="alert('Button with type submit clicked!')">Submit</button> </form> </body> </html>
I tried similar thing using input tag for button and having input type as submit which trigger the submit onclick on enter key press in the text field
<input type="submit" value="Click me" onclick="alert('Button with type button clicked!')">
pretty interesting..