skip to Main Content

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


  1. Chosen as BEST ANSWER

    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!


  2. The script should have the body tag.

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <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">submit</button>
        </form>
    
    
        <script src="script.js"></script>
    </body>
    
    </html>
    

    script.js

    $(document).ready(function () {
      $(document).on("submit", "#myForm", function (e) {
        e.preventDefault();
        let formData = $("#name").val();
        console.log(formData);
        e.target.reset()
      })
    })
    
    

    Test Case here:demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search