2013-05-07 97 views
2

表單停止提交以進行錯誤檢查,但在檢查完成後;它不會提交。檢查表單錯誤;但現在表格未能提交

我做了一個fiddle here向你展示我的意思。

如果您點擊'添加'空輸入。該錯誤顯示爲應該。但是,在你糾正錯誤並正確填寫表格之後。它未能提交從不點擊:alert('submitted');

我的代碼:(更新!)Fiddle here請看看

$(document).ready(function() { 
    required = ["id_name", "id_location", "id_start_date", "id_about"]; 
    emptyerror = "Please fill out this field."; 
    $("#eventForm").submit(function(e){ 
     e.preventDefault(); 
     var id = $(this).attr('id'); 
     var errorText = ''; 
     for (i=0;i<required.length;i++) { 
      var input = $('#'+required[i]); 
      if ((input.val() == "") || (input.val() == emptyerror)) { 
       input.addClass("tobefixed"); 
       input.css('border','2px solid #CF4046'); 
       input.val(emptyerror); 
      } else { 
       input.removeClass("tobefixed"); 
      } 
     } 
     if ($(":input").hasClass("tobefixed")) { 
      return false; 
     } else { 
      return true; 
     } 
    }); 
    $(":input").focus(function(){ 
     if ($(this).hasClass("tobefixed")) { 
      $(this).val(""); 
      $(this).removeClass("tobefixed"); 
      $(this).css('border', '2px solid rgb(187, 209, 236)'); 
     } 
    }); 
}); 

我怎樣才能使表單提交?提前謝謝你的幫助。

+0

什麼是錯誤通知。 – 2013-05-07 19:28:27

+0

後面的代碼將不會被執行。 '返回false;警報(「我永遠不會被執行!」); document.body.innerHTML =「」;' – 2013-05-07 19:29:33

+0

一旦你e.preventDefault(),你必須在你完成驗證後開始提交。 – iGanja 2013-05-07 19:57:50

回答

2

您正在返回如果沒有驗證消息,返回

if ($(":input").hasClass("tobefixed")) { 
      return false; 
     } else { 
      return true; // it goes back from here 
     } 

除了這個,你需要註釋你之前評論你的返回true或地方警報最後

返回假

更新fiddle

您將

e.preventDefault();

雖然您沒有任何驗證錯誤,但它會停止表單提交。

看到這fiddle

+0

請看看這個小提琴:http://jsfiddle.net/HgEnS/1/。它實際上並沒有提交。 – Modelesq 2013-05-07 19:35:03

+0

@Modelesq請參閱更新 – mprabhat 2013-05-07 19:43:46

+0

+1這至少解決了OP已阻止使用e.preventDefault()的默認操作的問題;老實說,他可能只是刪除那條線,一切都會奏效。 – iGanja 2013-05-07 20:04:00

1

刪除或評論return false;正上方的警報。你也在強制返回以上的if/else

1

return語句後的代碼從不執行。

return false; 
    alert('submitted'); // this never hits. Why is that? 

should be 

alert('submitted'); // this hits. 
    return false; 

更新:

if ($(":input").hasClass("tobefixed")) { 
      return false; 
     } 

     alert('submitted'); 
+0

請看看這個小提琴:http://jsfiddle.net/HgEnS/1/。它實際上並沒有提交。 – Modelesq 2013-05-07 19:34:12

+0

你的陳述是真實的,但我不認爲它解決了這個問題。 e.preventDefault()停止提交。 – iGanja 2013-05-07 20:00:17