Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a form from submitting when a specific field is empty? Pending Review
Asked on Apr 14, 2026
Answer
To prevent a form from submitting when a specific field is empty, you can use JavaScript to check the field's value and stop the form submission if the field is empty.
<!-- BEGIN COPY / PASTE -->
<form id="myForm">
<input type="text" id="myField" placeholder="Enter text" required>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("myForm").addEventListener("submit", function(event) {
var myField = document.getElementById("myField").value;
if (!myField) {
event.preventDefault();
alert("The field cannot be empty.");
}
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "submit" event listener is attached to the form to intercept the submission process.
- "event.preventDefault()" is used to stop the form from submitting if the field is empty.
- The "alert" function provides user feedback when the field is empty.
Recommended Links:
