简体   繁体   中英

What is the default behavior of the 'return' key in an HTML form?

I have always believed that the default behavior of hitting the 'Return' key was to submit the form. But it seems to be more complex: if there is a nearby button, the 'Return' key instead seems to simulate a 'click' event on that button, instead of submitting the form. Here's an example:

 document.querySelector('form').onsubmit = ev => { ev.preventDefault(); document.querySelector('#result').innerText = ev.target.elements.text.value; }; document.querySelector('#troublesome').onclick = ev => { ev.preventDefault(); ev.target.innerText = Math.random(); };
 <form> <input type="text" name='text' value='something' /> <button id="troublesome">Trouble</button> <button>Submit</button> </form> <div id="result">not submitted</div>

Above, when you hit return in the <input> element, the browser chooses to click the "Troublesome" button. But why? What exactly is happening here? And where can I read it in the specs?

Both button elements have no type set. Type=submit "is the default if the attribute is not specified for buttons associated with a <form> " ( MDN Webdocs ) and troublesome is the next after the input field. If you change its type to 'button', 'submit' will submit.

From MDN as well: "Note that the submit event fires on the element itself, and not on any or inside it. However, the SubmitEvent which is sent to indicate the form's submit action has been triggered, includes a submitter property, which is the button that was invoked to trigger the submit request. If the submission was not triggered by a button of some kind, the value of submitter is null. (If there's no element type=submit and Enter is pressed inside the input, the form will submit with event.submitter = null)

The logic seems to be "find the closest button to the focus that has type="submit", and simulate a click event on that button, else fall back to just submitting the form" (didn't find this explicitly somewhere) In your example 'troublesome' is of type 'submit' and closest to the input, and if there wasn't the 'prevent.default()', both events would be triggered.

 document.querySelector('form').onsubmit = ev => { ev.preventDefault(); document.querySelector('#result').innerText = ev.target.elements.text.value; }; document.querySelector('#troublesome').onclick = ev => { ev.preventDefault(); ev.target.innerText = Math.random(); };
 <form> <input type="text" name='text' value='something' /> <button type="button" id="troublesome">Trouble</button> <button>Submit</button> </form> <div id="result">not submitted</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM