View Full Version : I want to detect linebreak char in text input

12-24-2007, 10:38 AM
function detectNL(elem) {
var lastChar = elem.value.substr(elem.value.length-1,1);
if (lastChar == "\r\n") {
alert("detected nl char");

here is the form element:

<form name="form">
<input type="text" name="testField" value="" onkeyup="detectNL(document.form.testField);" />

Basically I want to detect when the enter button is pressed or when a linebreak character is typed into the field. (how you ask a linebreak character can be manually type? well you can paste on in with ctrl v)
Above is my attempt

1. I'm not really sure how to detect the character at all in JS, I know windows linbreaks are \r\n
linux \n
mac \r
2. Maybe I need to detect the keystroke event on the field? I have no idea how to do this as well..
3. The text field won't let you press enter at all, it will switch focus or try to submit form.. etc.. if you press the enter button, so I suppose detecting the keys pressed while the focus is on that element is necessary in order to detect when the enter key is pressed....

Above is my attempt, I just want to see a solution to my above description, you can stray from my original attempt if you like...
Thank you.

Philip M
12-24-2007, 11:41 AM
<script type = "text/javascript">

document.onkeyup = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if (key == 13) {
alert ("Newline detected");