Categories
JavaScript Answers

How to stop an input field in a form from being submitted with JavaScript?

Spread the love

To prevent an input field in a form from being submitted using JavaScript, you can intercept the form submission event and perform some validation or actions before allowing the submission to proceed.

To do this we write:

HTML:

<form id="myForm">
    <input type="text" id="myInput" name="myInput">
    <button type="submit">Submit</button>
</form>

JavaScript:

document.getElementById("myForm").addEventListener("submit", function(event) {
    // Prevent the default form submission
    event.preventDefault();

    // Your validation or actions here
    var inputValue = document.getElementById("myInput").value;

    // Example validation: Prevent submission if the input value is empty
    if (inputValue.trim() === "") {
        alert("Please fill out the input field.");
        return false; // Prevent form submission
    }

    // If validation passes, you can proceed with form submission programmatically
    // Optionally, you can submit the form using JavaScript:
    // this.submit();
});

This script intercepts the form submission event and prevents its default behavior using event.preventDefault().

Then you can perform any validation or actions you need.

If the validation fails, you can prevent the form from being submitted by returning false from the event listener function.

If validation passes, you can optionally submit the form programmatically, or let it submit naturally by removing the return false statement.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *