这应该很简单,但它让我疯狂。我有一个html5表单,我提交与ajax。如果您输入的值无效,则会显示弹出式响应。在运行我的ajax提交之前,如何检查条目是否有效?
形成:
<form id="contactForm" onsubmit="return false;"> <label for="name">Name:</label> <input type="text" name="name" id="name" required placeholder="Name" /> <label for="subject">Subject:</label> <input type="text" name="subject" id="subject" required placeholder="Subject" /> <label for="email">Email:</label> <input type="email" name="email" id="email" required placeholder="email@example.com" /> <label for="message">Message:</label> <textarea name="message" id="message" required></textarea> <input type="submit" id="submit"/> </form>
提交:
$('#submit').click(function(){ var name = $("input#name").val(); var subject = $("input#subject").val(); var email = $("input#email").val(); var message = $("input#message").val(); var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ; $.ajax({ url: "scripts/mail.PHP",type: 'POST',data: dataString,success: function(msg){ disablePopupContact(); $("#popupMessageSent").css("visibility","visible"); },error: function() { alert("Bad submit"); } }); });
解决方法
默认情况下,jQuery不了解HTML5验证的任何内容,因此您必须执行以下操作:
$('#submit').click(function(){ if($("form")[0].checkValidity()) { //your form execution code }else console.log("invalid form"); });