1<p><input type="text" data-max-words="2" data-announce="true"></p>
2<p><input type="text" data-max-words="3"></p>
3<p><input type="text" data-max-words="4"></p>
4<p><textarea data-max-words="100" rows="5" style="width:100%" data-announce="true"></textarea></p>
1// Get all inputs that have a word limit
2document.querySelectorAll('input[data-max-words]').forEach(input => {
3 // Remember the word limit for the current input
4 let maxWords = parseInt(input.getAttribute('data-max-words') || 0)
5 // Add an eventlistener to test for key inputs
6 input.addEventListener('keydown', e => {
7 let target = e.currentTarget
8 // Split the text in the input and get the current number of words
9 let words = target.value.split(/\s+/).length
10 // If the word count is > than the max amount and a space is pressed
11 // Don't allow for the space to be inserted
12 if (!target.getAttribute('data-announce'))
13 // Note: this is a shorthand if statement
14 // If the first two tests fail allow the key to be inserted
15 // Otherwise we prevent the default from happening
16 words >= maxWords && e.keyCode == 32 && e.preventDefault()
17 else
18 words >= maxWords && e.keyCode == 32 && (e.preventDefault() || alert('Word Limit Reached'))
19 })
20})