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.
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
textarea and the user presses a key, nothing will happen.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With