views:

427

answers:

5

Hello! I would like to ask somebody how i can determine what key was pressed in a textarea.... need to write a little javascript code.. a user type in a textarea and i need to write it in a while he writing so the keydown, keypress event handle this functionality, also need to change the text color if a user typed a "watched" word (or the word what he wrote contains the "watched" word/words ) in the textarea.. any idea how i can handle it ??

till now did the text is appear in the <div>, but with this i have a problem.. can't check if the text is in the "watched"... the document.getElementById('IDOFTHETEXTAREATAG'); on keypress is not really works because i got back the whole text inside of the textarea.....

So how i can do it ? any ideas ??? "(Pref. in Mozilla FireFox)

+1  A: 

Well, if you were using jQuery, you could do this given that the id of your textarea was 'ta':

$('#ta').keypress(function (evt) {
  var $myTextArea = $(this); // encapsulates the textarea in the jQuery object
  var fullText = $myTextArea.val(); // here is the full text of the textarea
  if (/* do your matching on the full text here */) {
    $myTextArea.css('color', 'red'); // changes the textarea font color to red
  }
};
Matthew Taylor
A: 

I suggest you use the 'onkeyup' event.

$( element ).keyup( function( evt ) {
    var keyPressed = evt.keyCode;
    //...
});
A: 

I am not sure what your problem is, the problem/question is described too vague. But I think that you confused what all the key* events do. Here's a clear overview:

  • onkeydown will be fired when the key is pressed, but BEFORE the character is appended to the value.
  • onkeypress will be fired when the key is pressed, but AFTER the character is appended to the value.
  • onkeyup will be fired when the key is released and that's always AFTER the character is appended to the value.

Maybe your actual problem was accessing the character by textarea's value instead of the keyevent.

Hope this helps.

BalusC
A: 

I have this made like this (plain JS, no JQuery):

function keyDown(e) { 
    var evt=(e)?e:(window.event)?window.event:null; 
    if(evt){ 
       if (window.event.srcElement.tagName != 'TEXTAREA') {
     var key=(evt.charCode)?evt.charCode: ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
        }
     }
} 
document.onkeydown=keyDown;

This script is in head tag. I am catching this in all textarea tags. Modify it for your purpose.

Trick
Maybe you should use a little less trenary operators (or whatever they are called in javascript) They make the code very unreadable.
Pim Jager
Trick
A: 
Alex