I’m using event.preventDefault on a form submission and it works, but only on desktop devices. When using a mobile device the form is submitted the normal way and the event is not prevented.
Here’s what my setup looks like:
index.html
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"
integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
<input id="name">
<button type="submit">
</form>
</body>
<script src="script.js"></script>
script.js
$(function() {
$("#myForm").submit(function (event) {
event.preventDefault();
let formData = $("#name").val();
console.log(formData);
});
2
Answers
This was related to a project hosted using GitPages. It turns out that the cause of the problem was that I was trying to reference a script from outside the folder the page was hosted from. The page was hosted from docs/index.html, and I was trying to reference the script using ../dist/script.js
While looking into it more, I stumbled upon this question which says GitPages doesn't allow that since technically only everything in the docs folder is hosted and the dist folder didn't exist. Not sure why it worked only on my computer...
I updated my reference to the script to its jsDelivr URL and everything now works as expected.
Thank you to everyone who offered help!
The script should have the body tag.
script.js
Test Case here:demo