3

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?

Josh Wood
  • 1,598
  • 3
  • 16
  • 21
  • 1
    maybe you could use the onchange event of your textarea to check the length of its content then if the content is smaller and if the content does'nt start with "C:>" you replace the string??? – Sebastien Aug 19 '13 at 12:01

2 Answers2

4

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);
    }
}
Bryce
  • 6,440
  • 8
  • 40
  • 64
  • Wow this is good! I never tought I could use indexOf this way! this is cool and usefull. Thanks! – Sebastien Aug 19 '13 at 12:05
  • This code only checks if requiredText is in the input text; it does not checks, however, that 1.) the text begins with the requiredText (as it is required in this case) 2.) may destroy user input, e. g. "C:>somefolder/somefile.txt" is the input value, user deletes ":>" => the new value of the textarea will be "C:>" - from a user's perspective, this can be really frustrating IMHO – Blasius Secundus Aug 19 '13 at 12:17
3

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.

Community
  • 1
  • 1