0

How can you make the keypress action work? Got a chat, with which i want to send - what else - messages. In the Form-tag (its jsp based) i got this:

" name="chat" target="content" onkeypress="Javascript: if (event.keyCode==13) SendMessage();" OnSubmit='SendMessage();return false;'>

the function in the script is the following:

    function SendMessage()
       {
         if (event.keyCode===13) {
           alert('ENTER PRESSED'); // to make sure the function is called
           document.chat.submit();
           document.chat.msg.value = "";
           document.chat.reset();
           document.chat.msg.focus();
        }
     }

This is working fine on Chrome but not on Firefox, but it should work on every Browser. In addition, this script causes firefox to not clear the textfield (i think, because the function is not called properly). Any suggestions or help on this? i'm pretty lost..

arserenko
  • 3
  • 2

4 Answers4

0

Here is a solution.

function SendMessage(event){
var x = event.which || event.keyCode;
if (x === 13){
//your code
}
}

The keyCode property may not work on the onkeypress event in Firefox. However, the which property does.

if the browser supports event.which, then use event.which, otherwise use event.keyCode

tkay
  • 1,716
  • 14
  • 18
0

keep html

" name="chat" target="content" onkeypress="Javascript: if (event.keyCode==13) SendMessage();" OnSubmit='SendMessage();return false;'>

and change function to this

function SendMessage()
{
    alert('ENTER PRESSED'); // to make sure the function is called
    document.chat.submit();
    document.chat.msg.value = "";
    document.chat.reset();
    document.chat.msg.focus();
}
Mark Lee
  • 301
  • 1
  • 2
  • 9
0

Try onkeyup:

var chat = document.chat;// chat form
var send = function() {
  chat.msg.value = '';
  chat.msg.focus();
};

var trySend = function(e) {
  e = e || event;
  var k = e.keyCode || e.which;
  if (13 === k)
    send();
};
<form name='chat' onsubmit='send();return false;'><!-- won't submit form -->
  <textarea name='msg' onkeyup='trySend(event)'></textarea>
  <button>Send</button>
</form>
  • holy crap this worked. i now got what you told. also this was a probelm of the "keypressed". keyup fixed it as well. thanks alot! – arserenko Apr 02 '15 at 06:44
0
$('form[name="chat"]').on('keyup', function(e){
        if (e.which === 13) {
            alert('ENTER PRESSED'); // to make sure the function is called
            document.chat.submit();
            document.chat.msg.value = "";
            document.chat.reset();
            document.chat.msg.focus();
        }
});
kayz1
  • 7,260
  • 3
  • 53
  • 56