Josh Wood
Josh Wood

Reputation: 1696

HTML textarea prevent some text from being deleted

I am making a terminal window in HTML/JavaScript and am using a textarea for input. I would like to prevent sections of the text in the textarea from being deleted. For example, if I had the text in the textarea "C:\>Random Code" I would like to prevent the user deleting the "C:\>" text. Is this possible using javascript?

Upvotes: 3

Views: 6141

Answers (2)

Blasius Secundus
Blasius Secundus

Reputation: 171

You cannot make a section of textarea uneditable (only the whole control).

You can use various JavaScript trickery (listening to keypress events and cancelling event using event.preventDefault if the user wants to do something that you do not want to allow)

Another solution is to, instead of having an undeletable section of the input, to automatically append (or prepend ) a predefined string to the user input (and conveneintly display it for the user in some way).

Update:

So, my solution would look like this:

var requiredText = 'C:>';
$('textarea').on('keyup',function(event) {
    if (GetSelectionStart(this) < requiredText.length){
event.preventDefault();
event.stopPropagation();
}

}

Where GetSelectionStart is a function that tells the beginning of the selected text (or caret position, if no text range is selected). For some possible implementations, see e. g. Caret position in textarea, in characters from the start

This function assumes that requiredText is always at the beginning of the string. But of course, it can be adapted for more complex scenarios.

Upvotes: 3

Bryce
Bryce

Reputation: 6610

Assuming jQuery, this script will listen for keystrokes, and if any of the required text can't be found (ie: user tries to delete it) it will add itself right back in there:

var requiredText = 'C:>';
$('textarea').on('input',function() {
    if (String($(this).val()).indexOf(requiredText) == -1) {
        $(this).val(requiredText);
    }
}

Upvotes: 4

Related Questions