My form consists of multiple input fields with validations. Initially, the submit button is disabled. Each time I enter a field, the validation function should run immediately. After all fields are filled with valid input, the submit button should be enabled. However, the code I tried below does not seem to work.
if($('input').val() == true) {
$('.myButton').prop("disabled", false);
}
I need assistance resolving this issue.
JavaScript (JS)
function validateForm() {
val = true;
var firstName = $('#firstname').val();
if (!firstName) {
$('#firstname').siblings(".error").addClass('alert-on');
val = false;
}
var lastName = $('#lastname').val();
if (!lastName) {
$('#lastname').siblings(".error").addClass('alert-on');
val = false;
}
var input = $('#email');
var re = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var is_email = re.test(input.val());
if (!is_email) {
$('#email').siblings(".error").addClass('alert-on');
val = false;
}
return val;
}
$(function () {
$('.myButton').prop("disabled", true);
$("input").on("change keyup paste", function () {
if (!$(this).val()) { $(this).siblings('.error').addClass('alert-on'); }
else { $(this).siblings('.error').removeClass('alert-on'); }
});
if($('input').val() == true) {
$('.myButton').prop("disabled", false);
}
$("#form").submit(function (event) {
if (validateForm()) {
return;
};
event.preventDefault();
});
})
HTML Markup
<form id="form">
<div class="">
<input type="text" placeholder="First name*" id="firstname">
<div class="error">Required</div>
</div>
<div class="">
<input type="text" placeholder="Last name*" id="lastname">
<div class="error">Required</div>
</div>
<div class="">
<input type="email" id="email" name="email" placeholder="Email">
<div class="error">A valid email address is required</div>
</div>
<div class="">
<input type="text" placeholder="Phone*" maxlength="12" id="phone">
<div class="error">Required</div>
</div>
<div id="form_submit">
<button class="myButton" type="submit">
Submit
</button>
</div>
</form>
Cascading Style Sheets (CSS)
input {
display: list-item;
margin-bottom: 10px;
}
.error {
display: none;
color: red;
}
.alert-on {
display: block;
}
.myButton{
height: 40px;
width: 90px;
}