问题
I am developing an application which needs a part of text in the textarea undeletable while they can add their text to the textarea.
For example when user come to a web page it has a textarea which has a text {username} of that user. The user can add more text like {username} hi the the earth is globe but should be unable to delete {username} from that textarea.
I am using Jquery as the javascript class, any idea that we can achieve it in Jquery?
回答1:
I think the only way to do this would be to perform a validation to make sure they didn't delete {username}, and display an error message (maybe auto-insert {username} at the beginning of the textarea as well) if they did.
However I agree with Luis that this is a difficult route to take. What about just displaying their username in a readonly field and giving them a textarea to add their own content to be displayed after it?
回答2:
Not sure at all but I got this and it still need to be improved a lot
<script>
$(function (){
$('#txtarea').keyup(function (){check()});
})
var txt = "username";
//txt is reg exp
function check(){
var txtarea = $('#txtarea');
var val = $(txtarea).val();
if(val.match('^'+txt)){
//do nothing
}
else
{
$(txtarea).val(txt+" "+val);
}
}
</script>
<textarea id="txtarea">username</textarea>
<a href="#" onclick="check()">check</a>
[UPDATE]
<script>
$(function (){
$('#txtarea').keyup(function (){check()});
})
var txt = "username";
//txt is reg exp
function check(){
var txtarea = $('#txtarea');
var val = $(txtarea).val();
if(val.match('^'+txt)){
//do nothing
}
else
{
//this is quite a bit flawed
//and i m terrible with regex
//do try to become creative
val = val.replace('usernam', '');
val = val.replace('userna', '');
val = val.replace('usern', '');
val = val.replace('user', '');
val = val.replace('use', '');
val = val.replace('us', '');
val = val.replace('u', '');
$(txtarea).val(txt+" "+val);
}
}
</script>
<textarea id="txtarea">username</textarea>
<a href="#" onclick="check()">check</a>
回答3:
If you're text would be positioned in fixed front or end, I found a solution for each.
Fixed front: How to lock the first word of a textarea?
Fixed end: How to have a disabled text in textarea-like
Cheers!
来源:https://stackoverflow.com/questions/5125485/how-to-have-undeletable-wordspart-of-text-in-textarea