簡體   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