HTML / JavaScript: How to make the default text <textarea> undeletable?

Is there a way to make the default text for entering <textarea> invulnerable to the user? For example, if we had <textarea> like this:

<textarea>I like/dislike this site because</textarea>

The user should be able to complete the sentence "I like / dislike this site because", but he will never be able to delete this part.

I understand that there are simpler approaches for this problem, but I was asked to do it this way. In addition, the target site uses a prototype javascript framework, so it should either include a prototype or without a frame. jQuery cannot be used, as this will cause a conflict with the prototype.

Thank you very much in advance.

+4
source share
3 answers

You can make it look like part of a text field, even if it is not.

A simple jsfiddle example to demonstrate an idea

+10
source

I would fake it. This is dirty, but you cannot remove the default text: http://jsfiddle.net/2EMkF/3/ .

 function $(id) {return document.getElementById(id);} $('s').addEventListener('click', function() { $('t').setSelectionRange(33, 33) $('t').focus(); }); $('t').addEventListener('keyup', function() { if($('t').value.substring(0, 33) != ' '.times(33)) { $('t').value = ' '.times(Math.max( 33, $('t').value.firstspace()) ) + $('t').value.fromnospaces(); $('t').setSelectionRange(33,33); } }); function t() { if(this.selectionStart < 33) this.setSelectionRange(33,33); } $('t').addEventListener('keyup', t); $('t').addEventListener('click', t); String.prototype.times = function(n) { var r = ""; for(var i = 0; i < n; i++) r += this; return r; } String.prototype.firstspace = function() { for(var i = 0; i < this.length; i++) if(this[i] != ' ') return i; return -1; } String.prototype.fromnospaces = function() { return this.substring(this.firstspace()); } 
+2
source

This code will throw the default text back to the beginning of the text field if it does not appear after the user changes:

 <script type="text/javascript"> function fixText() { var textAreaElement = document.getElementById("mytextarea"); var searchPhrase = "I like/dislike this site because"; if(textAreaElement) { if(textAreaElement.value.indexOf(searchPhrase) != 0) { textAreaElement.value = searchPhrase + " " + textAreaElement.value } } } </script> <textarea id="mytextarea" onblur="fixText();" onchange="fixText();">I like/dislike this site because</textarea> 

I threw it together for only a minute or so, and it has some obvious flaws, such as the fact that if someone deletes only the UNACCEPTED text by default, they can get a strange result, for example: β€œI like / dislike this site because I like this site because it’s nice. " But I'm sure you can manipulate it to make it more efficient. Something like this might work in conjunction with the pimvdb answer.

I like Elian Ebbing's answer though, if your employer allows you to do it that way.

0
source

All Articles