Limit text in a textarea to the actual area of the element

Issue

Most questions I have seen when it comes to TextArea ask about limiting characters. I do not want this. I want to know how to limit the editable area of a TextArea html element to the actual textarea itself. Is this even possible?

Example:

Say I have a TextArea that is 30 columns by 4 rows. You could limit the text in this area to 120 characters, but that won’t stop a user from hitting return 5 times and already being past the given area I have set up for it. I don’t want a scroll bar to come up.

Is there any javascript that can fix this?

Solution

Copy the text into a visibility: hidden div with font styles equal to the textarea and a max-width that won’t let it go beyond your number of columns. If the height of the hidden copy of the text exceeds your limit, remove the text that was added.

The following is close to what you need. Unfortunately, it doesn’t nix the 5th row (after hitting enter on the 4th row) until you type something on it, and it can leave a couple characters on the 5th row (if you wrap to the 5th row from the 4th row). I’m uncertain how to refine the technique further.

var $measure = $('#measure');
var $input = $('#input');
var $output = $('#measurement');

var existingText = '';
$input.on('keyup', function(event) {
    $measure.html($input.val());
    $output.val($measure.width() + 'x' + $measure.height() + 'px');
    if ($measure.height() > 60) {
        $input.val(existingText.trim());
        $measure.html(existingText.trim());
    }
    existingText = $input.val();
});
#measure
{
    position: absolute;
    visibility: hidden;
    height: auto;
    width: auto;
    white-space: pre-wrap;
    
    /* set font style equal to style of textarea */
    font-family: monospace;
    font-size: 13px;
    letter-spacing: normal;
    line-height: normal;
    word-spacing: 0;
    word-wrap: break-word;
    max-width: 221px;
    border: 1x solid black;
    margin: 2px;
    padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="input" cols="30" rows="4"></textarea>
<div id="measure"></div>
<br>
<input type="text" disabled="disabled" id="measurement"/>

Answered By – Brian S

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.