Hi all,

I've created an html form with a textarea for comments. When I tab into the text area the cursor moves to the centre of the top line rather than the beginning.

How can I stop this and have it always tab to the beginning of the first line without leaving any space?

Thanks.

Dani AI

Generated

Good catch, — that is exactly the usual cause. Browsers preserve every character between <textarea> and </textarea>, including leading newlines and spaces produced by indentation. Those characters become part of the field value, so when you tab in the caret lands after them. See the spec/notes on the textarea element for details: MDN: <textarea> element.

Practical fixes:

  • Avoid putting a newline or spaces immediately after the opening tag; print the server value right after it and escape output to prevent XSS. Example:

    <textarea id="comments" name="comments" rows="20" cols="50"><?php echo isset($_POST['comments']) ? htmlspecialchars($_POST['comments'], ENT_QUOTES) : ''; ?></textarea>
  • If you want to strip accidental leading whitespace when processing input, use ltrim() or trim() on the server before saving or re-displaying.

If you need to force the caret to the very start after focus, set it via JS:

var ta = document.getElementById('comments');
ta.focus();
ta.setSelectionRange(0, 0);

(See PHP htmlspecialchars and MDN: setSelectionRange.) Note: trimming removes intentional leading spaces, so only trim when appropriate.

This is the code I am using:

<p>Comments:<br /> <textarea name="comments" rows="20" cols="50">
        <?php if(isset($_POST['comments'])) echo $_POST['comments']; ?>
          </textarea></p>

Nevermind. Fixed it. It seemed the whitespace in the tags was the issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.