You cannot attach events before the elements you attach them to has loaded
This works -
Plain JS
Recommended to use eventListener
// Should only be triggered on first page load
console.log('ho');
window.addEventListener("load", function() {
document.getElementById('my-form').addEventListener("submit", function(e) {
e.preventDefault(); // before the code
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
})
});
_x000D_
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
_x000D_
but if you do not need more than one listener you can use onload and onsubmit
// Should only be triggered on first page load
console.log('ho');
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
// You must return false to prevent the default form behavior
return false;
}
}
_x000D_
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
_x000D_
jQuery
// Should only be triggered on first page load
console.log('ho');
$(function() {
$('#my-form').on("submit", function(e) {
e.preventDefault(); // cancel the actual submit
/* do what you want with the form */
// Should be triggered on form submit
console.log('hi');
});
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<input type="text" name="in" value="some data" />
<button type="submit">Go</button>
</form>
_x000D_