2013-10-19 90 views
1

我使用jQuery,所以我不知道如何可以顯示錯誤消息後,我點擊提交按鈕只有在輸入字段爲空。如何檢查輸入字段爲空,在提交

下面的代碼我簡單的表格如何應用到它。

<form id="myid" name="myid" method="post" action="hook.php"> 

name : <input type="text" name="name" id="name"> 

age : <input type="text" name="age" id="age"> 

<input type="submit" id="submit" name="submit" value="Save" /> 

</form> 

我想顯示錯誤這樣

enter image description here

回答

5

正如有人已經提到,你應該看看使用外部庫進行驗證。這就是說,這似乎是它可能工作(see JSFiddle)

var $form = $("#myid"), 
    $errorMsg = $("<span class='error'>This field is required..!!</span>"); 

$("#submit").on("click", function() { 
    // If any field is blank, we don't submit the form 
    var toReturn = true; 
    $("input", $form).each(function() { 
     // If our field is blank 
     if ($(this).val() == "") { 
      // Add an error message 
      if (!$(this).data("error")) { 
       $(this).data("error", $errorMsg.clone().insertAfter($(this))); 
      } 
      toReturn = false; 
     } 
     // If the field is not blank 
     else { 
      // Remove the error message 
      if ($(this).data("error")) { 
       $(this).data("error").remove(); 
       $(this).removeData("error"); 
      } 
     } 
    }); 
    return toReturn; 
}); 
+0

這是完全完美〜非常感謝 –

1

您可以使用event.preventDefault停止默認動作發生。然後檢查你的條件,如果條件失敗則顯示錯誤,如果不是,則提交表格。

$("#submit").click(function(event) { 
    event.preventDefault(); 
    if($(this).val().length === 0) { 
    // display some error 
    } else { 
    $("#myid").submit(); 
    } 
}); 
-1

您可以使用輸入標籤的HTML5 required='required'選項...

1

真的,我建議你使用一些框架表單驗證。因爲這是常見的任務,並且已經完成了10萬次。有很多,例如ParsleyJquery plugin,但也有很多其他簡單和易於維護,只是谷歌的'表格驗證'

爲什麼已經實現的代碼比自定義更好的情況下:1 )它已經被編寫,測試和工作,2)你幾乎從不需要單一的驗證,並且真正驗證幾個參數的形式可能是一個挑戰,並可能導致大量的驗證代碼3)框架是DRYer,而且是一個真正的很多其他的東西。

0

我還建議您使用驗證框架,因爲您需要針對不同領域的更多驗證。使用MooTools Floor這是最可靠的驗證框架。 MooTool Floor