我正在使用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>
Run Code Online (Sandbox Code Playgroud)
我想表现出这样的错误

正如有人已经提到的那样,您可能应该使用外部库进行验证.也就是说,这似乎可能有用(参见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;
});
Run Code Online (Sandbox Code Playgroud)