我想验证具有“必需”属性的输入表单,但“e.preventDefault()”似乎不起作用。表单提交并且 POST 成功,但数据未经验证,我找不到问题出在哪里。
<form>
<label for="name" class="control-label">Name</label>
<input type="text" id="name" class="form-control" required>
<label for="phone" class="control-label">Phone Number</label>
<input type="text" id="phone" class="form-control" required>
<label for="email" class="control-label">Email address</label>
<input type="email" id="email" class="form-control" required>
<div id="form-response"></div>
<button class="btn btn-lg btn-primary btn-block" id="submit" type="submit" style="background-color:#28547C;">Request Appointment</button>
</form>
JS:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
JS fiddle :https://jsfiddle.net/yhgz55y0/
最佳答案
现在您正在使用点击事件而不是提交事件。如果您将其切换为:
$("#submit").submit(function(e) {...
验证有效。
关于javascript - 验证前提交Jquery表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50107286/