mmm*_*che 24 html javascript forms jquery
我正在尝试验证联系表单,并且我想在每个输入字段填写后创建某种"表单已完成"消息(一些输入是文本框,一些是单选按钮).
到目前为止,这是我的代码:
$(document).ready(function() {
$('.form:input').each(function() {
if ($(this).val() != "") {
$('.congrats').css("display", "block");
}
});
});Run Code Online (Sandbox Code Playgroud)
p.congrats {
display: none;
}Run Code Online (Sandbox Code Playgroud)
<div class="form">
<input type="text" />
<br />
<input type="text" />
</div>
<p class="congrats">Congrats!</p>Run Code Online (Sandbox Code Playgroud)
kar*_*m79 39
这应该让你开始:
$(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");
}
});
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
试试这个 :
$("#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();
});
Run Code Online (Sandbox Code Playgroud)
<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" />Run Code Online (Sandbox Code Playgroud)
这个使用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;
};
Run Code Online (Sandbox Code Playgroud)