簡體   English   中英

提交表單時檢查Javascript變量

[英]Checking a Javascript variable when submitting a form

我有一個使用jQuery函數驗證表單的簡單HTML表單。

JsFiddle在這里:

您會在jQuery代碼中注意到,我有一個名為flag的變量,該變量設置為0或1。

jQuery(function () {
jQuery("#ValidField").validate({
expression: "if (VAL){flag=1; return true; }else{flag=0; return false;}",
message: "Please enter the Required field"
});
jQuery("#ValidNumber").validate({
expression: "if (!isNaN(VAL) && VAL){flag=1; return true; }else{flag=0; return false;}",
message: "Please enter a valid number"
});
jQuery("#ValidInteger").validate({
expression: "if (VAL.match(/^[0-9]*$/) && VAL){flag=1; return true; }else{flag=0; return false;}",
message: "Please enter a valid integer"
});

jQuery("#ValidSelection").validate({
expression: "if (VAL != '0'){flag=1; return true; }else{flag=0; return false;}",
message: "Please make a selection"
});

jQuery("#ValidRadio").validate({
expression: "if (isChecked(SelfID)){flag=1; return true; }else{flag=0; return false;}",
message: "Please select a radio button"
});
jQuery("#ValidCheckbox").validate({
expression: "if (isChecked(SelfID)){flag=1; return true; }else{flag=0; return false;}",
message: "Please check atleast one checkbox"
});

jQuery('.AdvancedForm').validated(function () {
if (flag == 1) alert("Use this call RIGHT HERE to make AJAX submissions.");
});
});

請注意,最后一個jQuery語句中的if (flag == 1)是不必要的。 我把它放在那里,看看JS是否能識別變量(它能識別)。

如何檢查flag == 0並調用Javascript警報說“頁面錯誤”?

先感謝您。

我更新了代碼以修復(flag == 1)語法。

使用以下內容:

if (flag) {
   alert("Use this call RIGHT HERE to make AJAX submissions.");
} else{
   alert("Flag was 0 or what error message you want to show");
}

如前所述,您需要使用==進行比較,而不是使用=進行分配。 但是,由於flag是布爾值,並且將為1或0,因此可以僅將if(flag)用作true,並使用else語句評估false情況。

編輯 :要檢查何時無效,可以使用invalidHandler函數(這適用於jQuery Validation插件):

$( "#myform" ).validate({
  invalidHandler: function() {
    alert("There were errors on the page");
  }
});

請參閱: http//jqueryvalidation.org/Validator.numberOfInvalids/

編輯 :jQuery Live窗體驗證的驗證。

默認情況下,此驗證處於活動狀態,當您填寫表單時,如果驗證失敗,它將顯示消息。 您可能將偵聽器添加到表單提交中,並檢查驗證錯誤類。

jQuery('.AdvancedForm').submit(function(){
     if(jQuery('.AdvancedForm').find('.ValidationErrors').length){
        alert('There were errors on your form');
     }
});

請參閱: http//www.geektantra.com/2009/09/jquery-live-form-validation/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM