HTML5必填属性无效 [英] HTML5 required attribute not working
问题描述
我想在不刷新页面的情况下创建电子邮件联系表单。所以我在我的html文件中添加了jquery。我用html所需的属性ti检查字段是否为空。但是当我添加jQuery代码即时我的HTML代码,所需的属性不起作用。以下是我的代码。
I want to create a email contact form without refreshing the page. So i added jquery im my html file. I used html required attribute ti check if the fields are empty. But when i add jquery code im my html code, the required attribute doesn't work. Below is my code.
index.html
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Contact Form</title>
<link rel="stylesheet" media="screen" href="styles.css" >
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("send.php", $("#mycontactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
</head>
<body>
<form id="mycontactform" class="contact_form" action="" method="post" name="contact_form">
<ul>
<li>
<h2>Contact Us</h2>
<span class="required_notification">* Denotes Required Field</span>
</li>
<li>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="John Doe" required />
</li>
<li>
<label for="email">Email:</label>
<input type="email" name="email" id="email" placeholder="john_doe@example.com" required />
<span class="form_hint">Proper format "name@something.com"</span>
</li>
<li>
<label for="message">Message:</label>
<textarea name="message" id="message" cols="40" rows="6" required ></textarea>
</li>
<li>
<button class="submit" id="submit" style="cursor:pointer" type="submit">Submit Form</button>
<div id="success" style="color:red;"></div>
</li>
</ul>
</form>
</body>
</html>
我需要attibute才能工作,并且还需要jquery代码才能工作。有人可以帮我吗?
I need required attibute to work and also that jquery code to work. Can someone help me?
推荐答案
表单验证仅在表单的 submit
事件触发,除非您触发它别处。而不是像这样做AJAX:
Form validation is only triggered on the submit
event of the form unless you trigger it elsewhere. Do the AJAX there instead, like this:
$(document).ready(function(){
$('#mycontactform').submit(function(e){
e.preventDefault();
$.post("send.php", $(this).serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
});
});
这篇关于HTML5必填属性无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!