繁体   English   中英

Jquery基本表单验证

[英]Jquery basic form validation

我试图创建自己的基本表单验证,而不必诉诸沉重的,一刀切的插件,我已编写以下代码。 我重写它并重新开始的频率并不重要,我似乎无法让它工作。

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

功能:-

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();
    }
})

我一整天都在搞乱这件事,我很难通过谷歌找到答案。

由于您在.each()的匿名函数中创建了'checked'变量,因此对于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/

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();
    }
})

你可以使用jquery.validate()函数,它的参考URL是: http ://docs.jquery.com/Plugins/Validation

更正:

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();
}
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM