当光标在表单输入元素中但仍然提交时按下输入时停止页面刷新?

时间:2014-09-10 23:19:38

标签: javascript jquery html ajax

我一直在阅读许多与此相关的文章,但他们只展示了如何防止任何事情发生,而不仅仅是页面刷新。

但我需要这样做,所以当按下回车键时,文本字段是通过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>

3 个答案:

答案 0 :(得分: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 :(得分:0)

如果你有一个提交按钮(不是类型=&#34;按钮&#34;)并且绑定你的函数以提交表格的事件,浏览器将不再需要任何脚本,浏览器会为你做这个

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

DEMO

答案 2 :(得分:0)

在这里给出的建议后,这就是我想出来的,它是完全正常的,所以我想在这里添加它作为答案,所以其他有类似问题的人都可以查看我的解决方案。

<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>