Reputation: 619
I have a textarea element in html like this:
<textarea id="txtarea">some text</textarea>
I want the user to be able to add text to the text area but to make 'some text' readonly/not editable.
I this is the closest I have got to a solution with jquery:
$('#txtarea').text[0]('t');
$('#txtarea').text[0]('x'); //etc
this is not working because text0 is not a syntax error. does somebody know how to change the first words of a text area or mabye provide another solution I didnt think about? Thanks EDIT:
I don't want only a default text area text, but that it will be uneresable
Upvotes: 0
Views: 1438
Reputation: 42314
What I would recommend is to add a function on keyup
which checks the .val()
for the presence of the .text()
. If it is not found, set the .val()
equal to the .text()
. Because the .text()
is set on page load, and the .val()
is updated as you type, this way you'll be able to add new text to the <textarea>
, but it will always add back in the original text if it is removed.
This can be seen in the following, where the user is free to type new text, but if the <textarea>
doesn't contain the string some text
, the <textarea>
will be updated to contain it:
$('#txtarea').on("keyup", function() {
if ($(this).val().indexOf($(this).text()) === -1) {
$(this).val($(this).text());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txtarea">some text</textarea>
Upvotes: 1
Reputation: 340
You can´t really keep an user from editing the text within the textarea. It would also be confusing (don't really know your use-case).
You could maybe use TWO textareas, one, for the existing text (which is readonly) another, for the new text.
Another aproach, if you reaaally want to have all in the same textarea, is to keep the old text in a variable, then, when the use exits the textarea (blur event), make sure that the new text begins with the old text. If it doesn´t then do whatever (reset to old text, return focus to control, etc)
Upvotes: 1