如何锁定一个textarea的第一个字? [英] How to lock the first word of a textarea?

查看:154
本文介绍了如何锁定一个textarea的第一个字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我需要创建一个字符有限的textarea,但是在开始时会有一个单词,它们不能改变。

它需要成为textarea的一部分,但我不希望用户能够删除或编辑它。



我想我可以创建一个JQuery函数使用 blur()来防止用户退格,但是我也需要阻止他们选择那个词并删除它。

更新
我写了这个JQuery,这似乎很好!但是我喜欢下面的解决方案,因为它不需要Javascript。

 < script type =text / javascript> 
var $ el = $(textarea#message_create_body);
$ el.data('oldVal',$ el.val());
$ b $ el.bind('keydown keyup keypress',function(){
var header =Header:;
var $ this = $(this);
$ this.data('newVal',$ this.val());
var newValue = $ this.data(newVal);
var oldValue = $ this.data(oldVal );

//检查以确保头部未被移除
if(!(newValue.substr(0,header.length)=== header)){
$ (this).val(oldValue);
} else {
$(this).data('oldVal',$(this).val());
}
});
< / script>


解决方案如果您只是希望textarea显示前缀,您可以使用标签,更改位置并缩进textarea内容。用户不会注意到这个区别。



你可以看到它是如何工作的: http://jsfiddle.net/FLEA3/


Basically I need to create a textarea that is character limited, but will have a single word at the beginning, that they can't change.

It needs to be a part of the textarea, but I don't want users to be able to remove it or edit it.

I was thinking I could create a JQuery function using blur() to prevent the user from backspacing, but I also need to prevent them from selecting that word and deleting it.

UPDATE I wrote this JQuery which seems to work great! However I like the solution below as it requires no Javascript.

<script type="text/javascript">
    var $el = $("textarea#message_create_body");
    $el.data('oldVal', $el.val());

    $el.bind('keydown keyup keypress', function () {
        var header = "Header: ";
        var $this = $(this);
        $this.data('newVal', $this.val());
        var newValue = $this.data("newVal");
        var oldValue = $this.data("oldVal");

        // Check to make sure header not removed
        if (!(newValue.substr(0, header.length) === header)) {
            $(this).val(oldValue);
        } else {
            $(this).data('oldVal', $(this).val());
        }
    });
</script>

解决方案

If you just want the textarea to show a prefix, you can use a label, change the position, and indent the textarea content. User will not notice the difference.

You can see how it works here: http://jsfiddle.net/FLEA3/.

这篇关于如何锁定一个textarea的第一个字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆