Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();

    }
like image 338
Gram Avatar asked Jan 25 '26 08:01

Gram


1 Answers

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

});
like image 85
Pawan Nogariya Avatar answered Jan 27 '26 20:01

Pawan Nogariya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!