1

I'm trying to alert the user whenever he/she presses enter. I decided to use javascript for this. I have the following bit of html:

   <div id="all">
           <h1>Welcome to the awesome chat system.</h1>
           <input type="text" id="name"><br/>
           <textarea  rows='30' id="chatArea" disabled='true'>
           </textarea>
           <textarea id="writtenThing" onkeypress="keyfunction(e)"></textarea>
           <button id="send">Send</button>
    </div>

Here is the javascript:

       <script>
            function keyfunction(e)
            {

                if(e.keyCode == 13)
                {
                    alert("things to do...");
                }

            }

       </script>

However the problem that I'm facing is that even though I press enter inside the textarea my browser does not alert me. I'm sure I'm using a browser which supports this.

Bula
  • 2,398
  • 5
  • 28
  • 54

3 Answers3

2

Pass the event to the function:

   <textarea id="writtenThing" onkeyup="keyfunction(event)"></textarea>

Add some cross browser support:

        function keyfunction(e)
        {
            if(e.keyCode == 13 || e.which == 13)
            {
                alert("things to do...");
            }
        }

JS Fiddle: http://jsfiddle.net/3MF3h/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

Use the following javscript.

 document.getElementById("writtenThing").onkeypress = function (e) 
 {
    if (e.keyCode == 13)
  {
     alert("things to do...");
  }
  }
Dot_NET Pro
  • 2,095
  • 2
  • 21
  • 38
0

you can replace onkeypress with onkeyup/onkeydown

Also, correct the code with following:

onkeypress="keyfunction(event)"

ipradhansk
  • 352
  • 1
  • 10
  • 36