Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lock the first word of a textarea?

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>
like image 680
Trevor Gehman Avatar asked Mar 14 '12 15:03

Trevor Gehman


1 Answers

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

like image 98
TimPetricola Avatar answered Nov 03 '22 00:11

TimPetricola