Gram Gram - 2 years ago 75
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 name="form1">
<textarea name="msg" id="message">
<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;



Answer Source

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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download