我有一个表格,我希望所有的字段都被填写。如果单击一个字段,然后没有填写,我想显示一个红色背景。
这是我的代码:
$('#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').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关键字,如果你只是想引用一个单独的元素(前提是在上下文的后代/子代中有一个文本字段)。
其他回答
可以考虑使用jQuery验证插件。对于简单的必填项,它可能有点过分,但它足够成熟,可以处理您甚至还没有想到的边缘情况(我们在遇到它们之前也不会想到)。
你可以用类"required"来标记必填字段,在$(document).ready()中运行$('form').validate(),这就是它所需要的。
它甚至也托管在微软CDN上,以便快速交付:http://www.asp.net/ajaxlibrary/CDN.ashx
在模糊上做太有限了。它假设表单字段是重点,所以我更喜欢在提交时执行,并通过输入进行映射。在处理了多年花哨的模糊、聚焦等技巧后,让事情变得更简单会在重要的地方产生更多的可用性。
$('#signupform').submit(function() {
var errors = 0;
$("#signupform :input").map(function(){
if( !$(this).val() ) {
$(this).parents('td').addClass('warning');
errors++;
} else if ($(this).val()) {
$(this).parents('td').removeClass('warning');
}
});
if(errors > 0){
$('#errorwarn').text("All fields are required");
return false;
}
// do the ajax..
});
$('#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关键字,如果你只是想引用一个单独的元素(前提是在上下文的后代/子代中有一个文本字段)。
函数checkForm() { 返回$(“输入(type =文本)”)。Filter (function () { 返回$ ().val()。长度=== 0; }) . length; }
每个人都有正确的想法,但我喜欢更明确一点,并精简价值观。
$('#apply-form input').blur(function() {
if(!$.trim(this.value).length) { // zero-length string AFTER a trim
$(this).parents('p').addClass('warning');
}
});
如果你不使用.length,那么一个'0'的条目会被标记为坏的,一个5个空格的条目可以被标记为没有$的ok。修剪。祝你好运。