2012-05-11 66 views
0

我想创建我自己的基本表单验证,而不必诉诸重型的,一刀切的插件,我写了下面的代码。似乎没有多少时间我重写它,并重新开始,我似乎无法让它工作。jquery基本表单验证

这个想法是,脚本检查表单以查看是否所有字段都已完成,如果是,则从提交按钮中删除禁用的属性。

的功能: -

function checkForm(){ 
$('#contact :input').each(function(){ 
    if($(this).attr('value') == null){ 
    var checked = false; 
    } else { 
    var checked = true; 
    } 
}) 
if (checked == true){ 
    alert('all filled in'); 
    //remove disabled attribute from button 
} else { 
    alert('not completed'); 
    //add disabled attribute to button 
} 

} 

并调用该函数的代码: -

$('#contact :input').blur(function(){ 
    if ($(this).val() <= ''){ 
     $(this).next('.error').show(); 
    } else { 
     $(this).next('.error').hide(); 
     checkForm(); 
    } 
}) 

我一直是这样折腾了一整天,我在努力找到通过谷歌的答案。

+1

有可能是与你比较'如果($(本).VAL()<= ''){' – TRR

回答

1
function checkForm(){ 
    var checked = true; 
    $('#contact :input').each(function(){ 
    if(!$.trim($(this).val()).length) checked = false; 
    }) 
    if (checked){ 
    alert('all filled in'); 
    //remove disabled attribute from button 
    } else { 
    alert('not completed'); 
    //add disabled attribute to button 
    } 
} 

,并调用函数

$('#contact :input').on('blur', function(){ 
    if (!$.trim($(this).val()).length){ 
     $(this).next('.error').show(); 
    } else { 
     $(this).next('.error').hide(); 
     checkForm(); 
    } 
}) 
+0

补充一下,我之前做了'if(checked)':) - 这个例子似乎是在做我需要做的事情 - 谢谢切断代码。 – Andrew

0

修正:

function checkForm(){ 
$('#contact :input').each(function(){ 
if($(this).val() == ''){ 
    var checked = false; 
    } else { 
var checked = true; 
} 
}) 
if (checked == true){ 
alert('all filled in'); 
//remove disabled attribute from button 
} else { 
alert('not completed'); 
//add disabled attribute to button 
} 

} 

$('#contact :input').blur(function(){ 
if ($(this).val() == ''){ 
    $(this).next('.error').show(); 
} else { 
    $(this).next('.error').hide(); 
    checkForm(); 
} 
}) 
+0

感谢您的答案 - 我敢肯定,我以前尝试过这种方法,但我只是再试一次,它仍然没有触发底部的任何警报函数 – Andrew

+0

然后在$(this).val()上添加警报以检查您获得的值和您想要获得的值。 – Rizstien

+0

还会检查您为“已检查”字段获得了什么值 – TRR

1

既然你正在创建的“检查.each()的匿名函数内的变量,检查的变量在该函数外部对于if(checked == true)测试是不可用的(您会得到'checked is undefined'错误)这就是为什么你的警报不会触发。

尝试先在匿名函数外定义'checked'变量,然后相应地更新它。

function checkForm() { 

    var checked = true; 

    $('#contact :input').each(function() { 
     if ($(this).val() == '') { 
      checked = false; 
     } 
    }) 

    if (checked == true) { 
     alert('all filled in'); 
     //remove disabled attribute from button 
    } else { 
     alert('not completed'); 
     //add disabled attribute to button 
    } 

} 

$('#contact :input').blur(function() { 
    if ($(this).val() == '') { 
     $(this).next('.error').show(); 
    } else { 
     $(this).next('.error').hide(); 
     checkForm(); 
    } 
}) 

这里是一个jsFiddle的例子。 http://jsfiddle.net/DMLzK/1/

+0

我明白了为什么它现在失败了,谢谢。 – Andrew