I have a simple form like this:
<form>
<div>Name:</div>
<input name="firstname" id="typeTracking" type="text">
<input value="Submit" id="submitTracking" type="submit">
</form>
And some vanilla JS code to detect when the form is submitted:
document.addEventListener('submit', doFancyThings);
But the doFancyThings
function is only triggered if I click the submit button, not if I press the enter key on my keyboard. How can I, using only plain javascript, listen for the enter key submit event, to also trigger my doFancyThings
function?
I've had a look in the Event reference at MDN and as far as I understand the submit event is only triggered when "The submit button is pressed". However, as the form is undoubtly submitted on enter key press, it ought to be firing some sort of event too, I reckon.
According to submit - Event reference the "event is fired only on the form element, not the button or submit input." Which sounds a bit contrary to the previous quote, and even less understandable why my listener doesn't trigger on the enter key.
not if I press the enter key
Use a form
document.addEventListener('submit', doFancyThings); function doFancyThings(e) { console.log('Enter pressed') e.preventDefault() }
<form> <div>Name:</div> <input name="firstname" id="typeTracking" type="text"> <button value="Submit" id="submitTracking" type="submit">Click</button> </form>
try this
var form = document.querySelector("form"); form.onsubmit = function(e) { doFancyThings(); e.preventDefault(); // for preventing redirect }; form.onkeydown = function(e) { if (e.keyCode == 13) { doFancyThings(); e.preventDefault(); // for preventing redirect } }; function doFancyThings() { alert("hmmm"); };
<form> <div>Name:</div> <input name="firstname" id="typeTracking" type="text"> <input value="Submit" id="submitTracking" type="submit"> </form>
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.