Gram Gram - 6 months ago 19
Javascript Question

How to submit form with enter key when I have a button, not a submit

I have a form with a button submit type, and I would like it to submit when enter key is pressed. I don't know how to implement this with the JS function I call when submitting the form.

FORM:

<form name="form1">
<textarea name="msg" id="message">
</textarea>
<p id="button">
<input type="button" value="Enter" onclick="submitChat()" id="innerbutton"></p>


JS Function

function submitChat() {


var uname = document.getElementById('nameplace').innerHTML

var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();

var badname = uname.charAt(0);

if (msg != "" & badname != "<") {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4&&xmlhttp.status==200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}

}
xmlhttp.open('GET','insert.php?uname='+uname+'&msg='+msg,true);
xmlhttp.send();

}

Answer

Attach keydown event with the document and call your function if Enter is pressed

$(document).on("keydown",function(e){

   var keyCode = e.which || e.keyCode;
   if(keyCode == 13) // enter key code
   {
      submitChat();
   }

});
Comments