我正在尝试验证联系表单,并且我想在填写每个输入字段后创建某种“表单已完成”消息(某些输入是文本框,有些是单选按钮)。
到目前为止,这是我的代码:
$(document).ready(function() {
$('.form:input').each(function() {
if ($(this).val() != "") {
$('.congrats').css("display", "block");
}
});
});
p.congrats {
display: none;
}
<div class="form">
<input type="text" />
<br />
<input type="text" />
</div>
<p class="congrats">Congrats!</p>
答案 0 :(得分:38)
这应该让你开始:
$(document).ready(function() {
$(".form > :input").keyup(function() {
var $emptyFields = $('.form :input').filter(function() {
return $.trim(this.value) === "";
});
if (!$emptyFields.length) {
console.log("form has been filled");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<input type="text" /><br />
<input type="text" />
</div>
<p class="congrats"></p>
答案 1 :(得分:6)
试试这个:
$("#a").on('click',function () {
var bad=0;
$('.form :text').each(function(){
if( $.trim($(this).val()) == "" ) bad++;
});
if (bad>0) $('.congrats').css("display","block").text(bad+' missing');
else $('.congrats').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<input type="text" /><br />
<input type="text" />
</div>
<p class="congrats"></p><input style="width:100px" value="check" id="a" type="button" />
答案 2 :(得分:5)
这个使用jQuery的serializeArray
函数,因此您不必担心检查不同类型的字段或符合空字段的条件:
$.fn.isBlank = function() {
var fields = $(this).serializeArray();
for (var i = 0; i < fields.length; i++) {
if (fields[i].value) {
return false;
}
}
return true;
};
答案 3 :(得分:3)
$('#check').click(function () {
var allFilled = true;
$(':input:not(:button)').each(function(index, element) {
if (element.value === '') {
allFilled = false;
}
});
console.log(allFilled);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form">
<input type="text" /><br />
<input type="text" />
</div>
<p class="congrats"></p>
<input type="button" id="check" value="check" />
答案 4 :(得分:1)
jsFiddle:http://jsfiddle.net/7huEr/38/
$(document).ready( function()
{
// Iterate over each input element in the div
$('.form input').each(function()
{
// Add event for when the input looses focus ( ie: was updated )
$(this).blur( function()
{
// Variable if all inputs are valid
var complete = true;
// Iterate over each input element in div again
$('.form input').each(function()
{
// If the input is not valid
if ( !$(this).val() )
{
// Set variable to not valid
complete = false;
}
});
// If all variables are valid
if ( complete == true )
{
// Show said congrats
$('.congrats').show();
}
});
});
});
答案 5 :(得分:1)
现代香草解决方案:
// Returns True if all inputs are not empty
Array.from(document.querySelectorAll('#myform input')).every(
function(el){return el.value;}
)