Reputation: 127
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();
}
Upvotes: 3
Views: 5890
Reputation: 4552
This should work:
document.getElementById('innerbutton').onkeydown = function(e){
if(e.keyCode == 13){
// your submit function call here
}
};
keyCode 13 is Enter key.
Upvotes: 0
Reputation: 8960
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();
}
});
Upvotes: 2
Reputation: 943571
Use a real submit button and move your JavaScript from its click event to the form's submit event. Prevent the default behaviour of the form submission so that normal submission don't happen.
<form id="form1">
<textarea name="msg" id="message">
</textarea>
<p id="button">
<input type="submit" value="Enter">
</p>
and
document.getElementById("form1").addEventListener("submit", submitChat);
function submitChat(event) {
event.preventDefault();
// etc
Upvotes: 1