我有几个输入字段和验证。首先,“提交”按钮将被禁用。每次我输入字段时,验证功能都会立即起作用。在每个字段都填充了有效输入后,我想启用“提交”按钮,但是我尝试了以下一些代码,该代码不起作用。
if($('input').val() == true) {
$('.myButton').prop("disabled", false);
}
请帮助
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
<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>
CSS
input {
display: list-item;
margin-bottom: 10px;
}
.error {
display: none;
color: red;
}
.alert-on {
display: block;
}
.myButton{
height: 40px;
width: 90px;
}
答案 0 :(得分:1)
您需要遍历每个输入以验证是否通过。像这样:
http://jsfiddle.net/71cantq2/1/
var count = 0; // Set your count here
$("input").on("change keyup paste", function () {
if (!$(this).val()) { $(this).siblings('.error').addClass('alert-on'); }
else { $(this).siblings('.error').removeClass('alert-on'); }
// Go through each input and see if it passes
$('input').each(function(index, i){
var getInput = $(this).val();
var checkValidation = $(this).closest('div').find('.alert-on').length;
if(getInput == "" || checkValidation > 0){
count++;
}
})
// If everything passes, your button will be enabled
(count == 0) ? $('.myButton').prop("disabled", false) : $('.myButton').prop("disabled", true);
// Reset your count each time
count = 0;
});