简体   繁体   English

按下Enter键时调用JavaScript函数

[英]Call a javascript function when enter key is pressed

I have a chatbox where I'm using onclick attribute to call a function. 我有一个聊天框,在其中使用onclick属性调用函数。 I just want a help to call this function on pressing enter key using javascript. 我只需要一个帮助,就可以使用javascript按下Enter键来调用此函数。

<input id="Submit"  class="btn btn-primary btn-lg" type="button" value="Send Message" onclick="set_chat_msg()"/>

Javascript: Javascript:

function set_chat_msg()
{

    if(typeof XMLHttpRequest != "undefined")
    {
        oxmlHttpSend = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
       oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
    }
    if(oxmlHttpSend == null)
    {
       alert("Browser does not support XML Http Request");
       return;
    }

    var url = "chat_send_ajax.php";
    var strname="noname";
    var strmsg="";
    if (document.getElementById("txtname") != null)
    {
        strname = document.getElementById("txtname").value;
        document.getElementById("txtname").readOnly=true;
    }
    if (document.getElementById("txtmsg") != null)
    {
        strmsg = document.getElementById("txtmsg").value;
        document.getElementById("txtmsg").value = "";
    }

    url += "?name=" + strname + "&msg=" + strmsg;
    oxmlHttpSend.open("GET",url,true);
    oxmlHttpSend.send(null);
}

I got a tut on this. 我对此不满意。

I used this javascript: 我用这个javascript:

function checkEnter(e){ 
        var characterCode 
    if(e && e.which){
        e = e
        characterCode = e.which 
     }
    else {
        e = event
        characterCode = e.keyCode 
    }

    if(characterCode == 13){ 
        set_chat_msg();
        return false
    }
    else{
        return true
    }
    }

and then I called it in the text area onKeyPress="return checkEnter(event)" 然后在文本区域onKeyPress="return checkEnter(event)"调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM