2013-07-22 83 views
-2

我想創建電子郵件聯繫表單而不刷新頁面。所以我在我的html文件中添加了jquery。我用html所需的屬性ti檢查字段是否爲空。但是當我添加jQuery代碼即時我的HTML代碼,所需的屬性不起作用。以下是我的代碼。需要HTML5屬性不起作用

的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="[email protected]" required /> 
      <span class="form_hint">Proper format "[email protected]"</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代碼工作。有人能幫我嗎?

回答

3

Form validation只引發了submit事件,除非你觸發其他地方的形式。在那裏做AJAX,而不是像這樣:

$(document).ready(function(){ 
    $('#mycontactform').submit(function(e){ 
     e.preventDefault(); 
     $.post("send.php", $(this).serialize(), function(response) { 
      $('#success').html(response); 
      //$('#success').hide('slow'); 
     }); 
    }); 
}); 
2

當用戶點擊按鈕而不是提交表單時,您正在發送AJAX請求。更改.click().on('submit')並將其連接到形式,而不是按鈕:

$('#mycontactform').on('submit', function() { 
    ... 

演示:http://jsfiddle.net/QjPka/