Call a javascript function when enter key is pressed

133 views Asked by At

I have a chatbox where I'm using onclick attribute to call a function. I just want a help to call this function on pressing enter key using javascript.

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

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);
}
1

There are 1 answers

0
Incredible Saurav On BEST ANSWER

I got a tut on this.

I used this 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)"