我正在开发一个使用表单验证的php程序。我将“errorMessage”div留空,以便在无效条目时更新它。
下面是html / bootstrap代码。
<div class="container">
<large><h1>Get in touch!</h1></large>
<div class="alert alert-success" role="alert" id="successMessage"></div>
<div id="errorMessage"></div>
<form method="post">
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
<small class="form-text text-muted">We'll never share your email with anyone else</small>
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" class="form-control" id="subject" name="subject">
</div>
<div class="form-group">
<label for="question">What would you like to ask us?</label>
<textarea type="text" class="form-control" id="question" name="question" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submitButton">Submit</button>
以下是我的Jquery / Javascript代码。这是为了检查无效条目并将错误文本放在空白div中。
<script type="text/javascript">
$("form").submit(function (e) {
e.preventDefault();
var error= "";
var fieldsMissing = "";
var successMessage = "";
if($("#subject").val() == "") {
error += "<p>The subject field is missing</p>";
}
$("#errorMessage").html(error);
}
});