Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript textarea word limit

Tags:

javascript

I know that HTML has a maxlength attribute, but I want to limit the number of words typed not characters.

After 10 words the user should be able to move his cursor left & edit the text, but not add any more words.

So how can I stop the cursor?

Any suggestions?

Only javascript please.

like image 369
karkonosze Avatar asked Dec 28 '25 11:12

karkonosze


1 Answers

This doesn't cover all possible user actions, but I was bored and maybe you'll learn something:

HTML:

<textarea id="input_box"></textarea>

JavaScript:

function check_words(e) {
    var BACKSPACE  = 8;
    var DELETE     = 46;
    var MAX_WORDS  = 10;
    var valid_keys = [BACKSPACE, DELETE];
    var words      = this.value.split(' ');

    if (words.length >= MAX_WORDS && valid_keys.indexOf(e.keyCode) == -1) {
        e.preventDefault();
        words.length = MAX_WORDS;
        this.value = words.join(' ');
    }
}

var textarea = document.getElementById('input_box');
textarea.addEventListener('keydown', check_words);
textarea.addEventListener('keyup', check_words);

Try it on JS Bin: http://jsbin.com/isikim/2/edit

  • If there are 10 words in the textarea and the user presses a key, nothing will happen.
  • If a user tries to copy and paste a big chunk of text, the contents of the textarea will immediately be stripped down to just 10 words.

Actually, I'm not sure it matters that this isn't perfect. Since JavaScript runs on the client, you just need something that will work for a normal user. Malicious users can always screw with your JavaScript; no way around that. As long as you're doing real sanitation on the server, there should be no problem.

like image 66
user428517 Avatar answered Dec 31 '25 00:12

user428517