问题描述
基本上我需要创建一个字符有限的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>
你可以看到它是如何工作的:。
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.
UPDATEI 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的第一个字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!