williamcodes
williamcodes

Reputation: 338

Pressing `enter` key in a text area doesn't change the cursor index correctly

In javascript we can get the "index" of the cursor in a textarea element by using the element.selectionStart or element.seletionEnd properties of the text input element. So a text area of 40 columns, and 10 rows, should have a cursor position of 0-40 when on row 0 (the first row). However, when you press the enter key, which visually takes the cursor to the next line in the text input element, the cursor position doesn't update accordingly. In fact, pressing the enter key merely has the effect of adding a single blank to the text area, hence make the cursor position 1+ what it was before pressing the enter key. Why is that, and is there a way to have the intended effect of updating the cursor position to the next line?

I've included the following code snippet to better explain what I'm talking about.

var input = document.getElementById("PMCDefMsgtxt");

input.addEventListener("keyup", function(event) {
  // Number 13 is the "Enter" key on the keyboard
  if (event.keyCode === 13) {
    event.preventDefault();
    // should log to the console the cursor position
    console.log(input.selectionEnd);
  }
});
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <textarea rows="10" cols="40" class="fwMultilineTextbox" id="PMCDefMsgtxt" name="PMCDefMsgtxt"
  style="width: 550px; height: 125px; margin-left: auto;"></textarea>
</body>
</html>

Upvotes: 0

Views: 513

Answers (1)

Ross Sheppard
Ross Sheppard

Reputation: 870

The enter key actually inputs a line break character, so it will not count the rest of the columns but only the line break character instead.

If you're wanting to count the number of columns on every enter, you will have to define a variable that adds the number of columns to it on every enter. In other words, in your event listener, you will have to add that number, e.g., 40 - element.selectionEnd, to the variable when the keyCode equals 13.

Upvotes: 1

Related Questions