I have a textarea. the user types in there and when he's done, he presses enter on the keyboard. a function in javascript is called, which receives the text in the textarea and does something with it. when the user hits enter, the text in the textarea is cleared out and the textarea appears blank again. the problem is..my cursor drops to the next line after the user hits enter. I want the cursor to remain at the beginning on the first line of the textarea. How do I do this? here is my html code for the textarea: <textarea name="inputMessage" id="inputMessage" wrap="virtual" onkeydown="handleKeyIM(event, this.id)" rows="10" cols="50"></textarea><br/> Code (markup): here is the javascript: function handleKeyIM(e, elemID){ e = (!e) ? window.event : e; code = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0)); if (e.type == "keydown") { if(code == 13){ var elem = document.getElementById(elemID); var text = elem.value; //do something with text ... elem.value = ''; } } } Code (markup):
The problem is you're making it handle the data on keydown which means you're doing it before the enter key gets to insert what it normally would in a textarea; a new line. You'd have to do it on keypress or keyup but then it will have an extra new line in the data you're parsing (which you can easily remove yourself or just not worry about it) and then when you clear the value, it should be completely empty since you cleared it after the enter key got to do what it was meant to do.
you've got some good points there. I tried using the keypress event but that left me on the same spot. keypress leaves my cursor on the next line..keypress produced the same result as keydown....so i tried keyup and i ended up with a \n at the end of the string, as you mentioned....although, my cursor did go back to the beginning of the text area. I could remove the newline but then I would have to do a string.replace in such way that would accomdate the many disagreeing browsers.. so what I did was used 2 event handlers: onkeydown: retrieve text from textarea; onkeyup: textarea.value = ''; this brought the cursor to the beginning and did not add a newline to the end of the string...the cursor would move down to the next line because of the enter key, but its brought back to the first line immediately..... I wanted the cursor to sit still on the first line after enter is hit but I think I can live with the way it is now.... thanks for your input on this.