Search code examples
htmlrequired

HTML 'required' error firing way too late


I have below (much simplified) HTML and javascript code. When I leave the numDig field empty and click on the Save button, the required error shows up over the input field a little too late, and the page redirects. When the page is already redirecting and loading, the required error appears. Why does this happen and is there a way to fix this? Currently, I can submit the form without filling the required field.

I tried both button and input but they both do the same thing. The required error appears when the page is already redirecting.

<script>
    function saveSettings(){
        //More code here
        //and redirect to the previous page
    }
</script>
<form>
    <div class="space">
        <p> Enter the number you like </p>
        <input id="numDig" type="number" min="1" max ="6" required>
    </div>
    <div class="space">
        <button type="submit" onclick="saveSettings()">Save</button>
        <!--<input type="submit" onclick="saveSettings()" value="Save">-->
    </div>
</form>

Solution

  • You put the fuction in onsubmit for required to take effect properly

    <form onsubmit="saveSettings()">
        <div class="space">
            <p> Enter the number you like </p>
            <input id="numDig" type="number" min="1" max ="6" required>
        </div>
        <div class="space">
            <input type="submit">Save</button>
        </div>
    </form>