我有一个表格,我希望所有的字段都被填写。如果单击一个字段,然后没有填写,我想显示一个红色背景。
这是我的代码:
$('#apply-form input').blur(function () {
if ($('input:text').is(":empty")) {
$(this).parents('p').addClass('warning');
}
});
无论字段是否填写,它都应用警告类。
我做错了什么?
我有一个表格,我希望所有的字段都被填写。如果单击一个字段,然后没有填写,我想显示一个红色背景。
这是我的代码:
$('#apply-form input').blur(function () {
if ($('input:text').is(":empty")) {
$(this).parents('p').addClass('warning');
}
});
无论字段是否填写,它都应用警告类。
我做错了什么?
当前回答
你可以尝试这样做:
$('#apply-form input[value!=""]').blur(function() {
$(this).parents('p').addClass('warning');
});
它将只对空值的输入应用.blur()事件。
其他回答
$('#apply-form input').blur(function()
{
if( !$(this).val() ) {
$(this).parents('p').addClass('warning');
}
});
你不一定需要。length,或者看看它是否为>0,因为空字符串的值无论如何都是假的,但如果你为了可读性考虑:
$('#apply-form input').blur(function()
{
if( $(this).val().length === 0 ) {
$(this).parents('p').addClass('warning');
}
});
如果你确定它总是操作文本字段元素,那么你可以使用this.value。
$('#apply-form input').blur(function()
{
if( !this.value ) {
$(this).parents('p').addClass('warning');
}
});
此外,你应该注意$('input:text')抓取多个元素,指定一个上下文或使用this关键字,如果你只是想引用一个单独的元素(前提是在上下文的后代/子代中有一个文本字段)。
你可以尝试这样做:
$('#apply-form input[value!=""]').blur(function() {
$(this).parents('p').addClass('warning');
});
它将只对空值的输入应用.blur()事件。
<script type="text/javascript">
$('input:text, input:password, textarea').blur(function()
{
var check = $(this).val();
if(check == '')
{
$(this).parent().addClass('ym-error');
}
else
{
$(this).parent().removeClass('ym-error');
}
});
</script>// :)
:empty伪选择器用于检查元素是否不包含子元素,你应该检查它的值:
$('#apply-form input').blur(function() {
if(!this.value) { // zero-length string
$(this).parents('p').addClass('warning');
}
});
可以考虑使用jQuery验证插件。对于简单的必填项,它可能有点过分,但它足够成熟,可以处理您甚至还没有想到的边缘情况(我们在遇到它们之前也不会想到)。
你可以用类"required"来标记必填字段,在$(document).ready()中运行$('form').validate(),这就是它所需要的。
它甚至也托管在微软CDN上,以便快速交付:http://www.asp.net/ajaxlibrary/CDN.ashx