如何在textarea中有不可删除的单词(文本的一部分)

时间:2011-02-26 06:37:43

标签: jquery textarea

我正在开发一个应用程序,它需要textarea中的部分文本不可删除,同时他们可以将文本添加到textarea

例如,当用户访问网页时,它有一个textarea,其中包含该用户的文本{username}。用户可以添加更多文本,例如{username} hi the the earth is globe,但无法从该textarea中删除{username}

我使用Jquery作为javascript类,我们可以在Jquery中实现它吗?

3 个答案:

答案 0 :(得分:1)

我认为执行此操作的唯一方法是执行验证以确保它们不会删除{username},并显示错误消息(可能在开头时自动插入{username}如果他们这样做了textarea。

但我同意路易斯认为这是一条艰难的路线。那么只是在一个只读字段中显示他们的用户名并给他们一个textarea来添加他们自己的内容以便在它之后显示呢?

答案 1 :(得分:1)

根本不确定,但我得到了这个,但仍需要进行大量改进

<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>

答案 2 :(得分:0)

如果您的文本位于固定前端或末尾,我找到了解决方案。

固定前线:How to lock the first word of a textarea?

固定结束:How to have a disabled text in textarea-like

干杯!