How to lock the first word of a textarea?

孤街浪徒 提交于 2019-12-04 03:24:59

问题


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>

回答1:


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




回答2:


How about just putting this word as a label next to the textbox? It may be confusing for the users not to be able to edit part of the text in the textbox.




回答3:


Wouldn't it be better if you just alert the user that whatever he inputs in the textarea will be submitted with a "prefix" and then

  • show the prefix as a label before the textarea
  • add the prefix to the inputted text before submitting


来源:https://stackoverflow.com/questions/9704795/how-to-lock-the-first-word-of-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!