
Validating a Form Using jQuery
Edited
I want to validate a form before submission. The form should ensure that all required fields are filled out and display an error message if any field is left empty.
Asked 1/31/2024 9:07:08 PM
1 Answers

2
you can validate the form by checking if all required fields have been filled out. Use jQuery to iterate through each input field and check if it's empty. If any field is empty, display an alert message and prevent the form from being submitted.
$(document).ready(function() {
$('#submitForm').click(function() {
$('input[type="text"]').each(function() {
if ($(this).val() === '') {
alert('Please fill out all fields');
return false;
}
});
});
});
HTML:
<form id="myForm">
<input type="text" name="name" placeholder="Name">
<input type="text" name="email" placeholder="Email">
<input type="text" name="phone" placeholder="Phone">
<button type="button" id="submitForm">Submit</button>
</form>
Edited
Answered 1/31/2024 9:09:15 PM