2014-09-10 30 views
1

我一直在讀通過與此文章很多,但他們只展示瞭如何防止發生任何事情,不僅刷新頁面。當光標位於表單輸入元素但仍提交時按下回車鍵時停止刷新頁面?

但我需要的時候按下Enter鍵時文本字段通過一個Ajax請求提交無刷新頁面,就像我如何可以使用輸入型按鈕,一個onclick事件有它如此。

IV增加了一個非常基本的實物模型,說明您明白我的意思。

<html> 
    <head> 
     <title>Demo</title> 
     <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.2/jquery.min.js'></script> 
    </head> 
    <body> 
     <form id="someForm" action="" method="post"> 
      <!-- 
       below is an example of the text field 
       id like to submit but without the 
       page refreshing when "Enter" is pressed 
      --> 
      <input type="text" id="demoText"/> 
      <button type="button" id="postBtn" onclick="postText()">Post</button> 
     </form> 
     <script> 
      function postText() { 
       alert("Random Function..."); 
      } 
     </script> 
    </body> 
</html> 
+0

如果您有ajax功能,您應該將其添加到上面的代碼中,您無法提交沒有頁面重新加載的表單嗎? – adeneo 2014-09-10 23:22:25

+0

而使它工作的方法只是通過捕獲表單提交事件,而不是按鈕單擊事件。 – adeneo 2014-09-10 23:23:22

+0

@adeno謝謝你,我會考慮捕捉它,我不包括AJAX由於代碼量(PHP,jQuery和HTML),將需要爲它做這就是爲什麼我所做的模擬了感(它的在線電臺頁面所以不能擁有它擾亂流的每個職位/刷新)上聊天功能 – Parody 2014-09-10 23:33:18

回答

0

這裏給出的提醒後,這是我想出了,它是全功能的,所以想在這裏ID添加它作爲一個答案,以便其他人有類似的問題,可以查看我的解決方案。

<html> 
    <head> 
     <title>Demo</title> 
     <script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script> 
    </head> 
    <body> 
     <form id="form"> 
       <input type="text" class="input" id="chatTxt" placeholder="Chat post..."/> 
       <input type="button" id="submit" value="Submit"/> 
      </form> 

     <script type="text/javascript"> 
      $('form').keypress(function(e) { 
       var code = e.keyCode || e.which; 

       if(code === 13) { 
       e.preventDefault(); 
       $("#submit").click(); 

       }; 
      }) 
      $(document).ready(function(){ 
       $("#submit").click(function(){ 
       var ChatText = $("#chatTxt").val(); 

        if(ChatText ==''){ 
        alert("Chat text is empty!");  
        } 
        else{ 

        $.post("demo.php",{ ChatText1: ChatText }, 
         function(data) { 
         alert(data); 
         $('#form')[0].reset(); 
         }); 

        } 
       }); 
      }); 
     </script> 
    </body> 
</html> 
1

你可以這樣做來捕獲控件的按鍵事件 - 比如輸入框。

$(function() { 
    $('#demoText').keypress(function (e) { 
    var key = e.which; 
    if(key == 13) // enter pressed 
     { 
     postText(); 
     } 
    }); 
}); 

還有更多的例子here

要發佈使用Ajax,做這樣的事情:

var postText = function() { 
    var stuff = $.post("serverpage.php", function() { 
     alert("success"); 
    }).fail(function() { 
     alert("error"); 
    } 
)}; 
+1

大加讚賞感謝 – Parody 2014-09-10 23:33:46

+0

@Parody沒問題,很高興幫助。 – Donal 2014-09-10 23:35:20

0

無需任何腳本,瀏覽器會爲你做,如果你有一個提交按鈕(不是type =「button」)並綁定你的函數提交表單事件

<form id="someForm" action="" method="post" onsubmit="postText();return false"> 
    <input type="text" id="demoText" /> 
    <button type="submit" id="postBtn">Post</button> 
</form> 

DEMO

+0

真棒謝謝! – Parody 2014-09-10 23:42:15

相關問題