Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript detect a string is typed in textarea

Is there a way in javascript to detect if a word/string was typed in a textarea? I want to detect the string <svg> being inputed in Ace editor or CodeMirror and then do something else. Sounds like it has been implemented but I don't know how.

like image 213
enem Avatar asked Oct 19 '25 03:10

enem


1 Answers

It is possible in Javascript to bind to the key up/down/press/etc events on DOM objects. You have to set the appropriate attribute in the HTML.

<textarea onkeyup='checkText(this.value);'></textarea>

This is the key line that calls the Javascript function with the value (text) of the textarea.

Here is a complete example that demonstrates this use. Listening on Key Up is preferred since the new character will be in the text value before the function is called.

<html>
<head>
<script type='text/javascript' >
var oldText = '';

function checkText(text)
{
    if(text.length >= 1)
    {
        if(text == '<svg>' && text != oldText)
        {
            alert("<svg> found");
        }
    }
    oldText = text;
}
</script>

<body>

<textarea onkeyup='checkText(this.value);'></textarea>

</body>
</html>
like image 170
kr094 Avatar answered Oct 21 '25 16:10

kr094