在文本框中输入按下时提交ajax表单

时间:2017-07-07 07:40:54

标签: javascript php

我有一个文本框,是我的消息文本框。 目前,我的ajax表单只需点击一下按钮就可以了。 我猜是因为按钮的名字。

我想要它,以便当我在文本框中按Enter键时,它会提交表单但不刷新页面。

在输入上添加一些jquery会使我的页面刷新。

以下是刷新页面当前状态的代码。 我的工作状态只有一个按钮包含在此表格中:

// New map
var map = ...

// INSERT Lat Lng via django here

{% for location in add_list %}
    addMarker({coords:{
        lat: {{ location.latitude|stringformat:'f' }}, 
        lng: {{ location.longitude|stringformat:'f' }}
        }
    });
{% endfor %}

我的PHP脚本是:

    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control" type="text" name="chat" id="chatbox" placeholder="Type something.." />
        <input type='submit' name='send' id='send' class='btn btn-send' value='Send' />
    </form>

我的Javascript / Jquery是:`

    <form class="chat-form form -dark" method="POST" onsubmit="return submitchat();">
        <input class="form-control entryMsg" type="text" name="chat" id="chatbox" placeholder="Type something.." />
    </form>

4 个答案:

答案 0 :(得分:6)

添加keydown函数以运行该函数。

&#13;
&#13;
$("#txtSearchProdAssign").keydown(function (e) {
  
  if (e.keyCode == 13) {
   console.log("put function call here");
   e.preventDefault();
   submitchat();
  }
  
});

function submitchat(){
  console.log("SUBMITCHAT function");
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form type="post">
<input type="text" id="txtSearchProdAssign">
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将功能更改为此

    function submitchat(e){
    e.preventDefault();
// rest  code
}

答案 2 :(得分:0)

从下面的代码中,您可以在用户按下回车键

后调用ajax功能
$('#msg').keypress(function(e){

        if(e.keyCode == 13){
            var keyword   = this.value;
            console.log(keyword);
            if(keyword.length>0){

                $.ajax({
                    url: 'aj_support_chat.php',
                    method: 'POST',
                    data: {holder: 'chat_start',type: 'in',keyword: keyword,}, 
                    success: function(res){ 
                        console.log(res)
                        return false;
                    }       
                });
            }
        }
});

您还可以检查输入的文字是否有值

答案 3 :(得分:0)

在ajax调用中声明方法时,可以删除表单上的method="post"。在表单上使用POST方法将迫使其尝试提交表单,在这种情况下,表单将作为刷新。

<form class="chat-form form -dark" onsubmit="return submitchat();">
    <input class="form-control entryMsg" type="text" name="chat" id="chatbox" placeholder="Type something.." />
</form>
相关问题