andi
andi

Reputation: 21

Is it possible to indent the contents of an HTML textarea without displaying the indentation?

For example, the first line in the textarea below is not indented in the html code but the second is indented.

 <!DOCTYPE html>
    <html>
      <body>
        <textarea rows="4" cols="50">
    A line with no indentation but I would prefer if it were indented in the code
        A line that displays with unwanted indentation
        </textarea>
      </body>
    </html>

Upvotes: 1

Views: 577

Answers (2)

Vip3r
Vip3r

Reputation: 13

As cars10m mentioned, textarea displays whatever you type in it 'as-is'. However, you can use JavaScript in order to fix the content on page load and on input.

Example:

$(document).ready(function(){
    $(".sample").val($(".sample").val().replace(/\s\s+/g, ' '));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="4" cols="50" class="sample">
A line with no indentation but I would prefer if it were indented in the code
    A line that displays with unwanted indentation
</textarea>

Upvotes: 0

RickN
RickN

Reputation: 13500

A textarea element has the CSS property white-space set to pre by default. This preserves whitespaces in the element, rather than the default of ignoring them. The value pre-line does what you want: it preserves linebreaks, but not other whitespace. You can read about other options at MDN.

<!DOCTYPE html>
<html>
  <body>
      <textarea rows="8" cols="50" style="white-space: pre-line">
A line with no indentation but I would prefer if it were indented in the code
    A line that displays with unwanted indentation

          As a potentially unwanted side effect, 
          white-space     in-line    is ignored as well.
    </textarea>
  </body>
</html>

Run this snippet and you'll see that 'A line...' will wrap to a new line (because there is a linebreak) but it will not be indented.

Upvotes: 2

Related Questions