views:

20

answers:

1

Basically have a large textarea, and I want to be able to do a few things with it;

  1. Detect when the user presses "enter" to go to a new line,

    and

  2. When enter is pressed, if the line contains a certain string let's say "hello", a line would be written to the textarea that reads "hello to you."

I cannot, for the life of me, detect a string from within a textarea. I am a huge newb, though.

Much obliged.

A: 

I would use a JavaScript framework like jQuery for this purpose. The code would look something like this:

$(function() {
    $('textarea').keypress(function(event) {
        if (event.which == 13) { // Return key
            var textareaText = $(this).val();
            if (textareaText.match(/hello/)) {
                $(this).val(textareaText+"\nhello to you.");
            }
        }
    });
});
elusive
So I enter this word for word, and it should work? the $('textarea') would be the name of my textarea?
four33
`textarea` is a [jQuery selector](http://api.jquery.com/category/selectors/) that selects all `<textarea>`-elements on your page. Note that `/hello/` is a [regular expression](http://en.wikipedia.org/wiki/Regular_expression) and needs to be written as one. This is not as trivial as it might appear. You should probably read some tutorials before messing with this.
elusive
OK, so that didn't work. Am I to assume that this isn't working code?
four33
... This shit was so much easier in python. Elusive, if you use google chat or something similar, would you be at all willing to answer a few questions I have directly?
four33
This should be working code, but since i barely know your Markup, its really hard to guess what exactly you are looking for. And no, i do not use instant messengers. Sorry about that.
elusive
Well if jQuery selects all <textarea> elements, wouldn't it work regardless of markup?
four33
This won't work: the extra line will always be inserted at the end of the textarea, and will always append the extra line if the textarea value contains "hello" regardless of where the caret is.
Tim Down