Elinoter99
Elinoter99

Reputation: 619

Set maximum number of words HTML textbox

I want to set a maximum number of words the user can type in a textbox, not the number of character but words.
This is possible?

I did some digging and found out how to get the number of words the user has inputted using regular expressions, but im not sure how to stop the user from entering more letters after reaching the max

var jobValue = document.getElementsById('textBox1').value
var words = jobValue.value.match(/\S+/g).length;
if(words>=2){
   //stop inputs
}

PS.
I want to limit the number of words to 2.

UPDATE

function wordLimit(){
    
       var jobValue = document.getElementById('wordIntent').value
       var words = jobValue.value.split(/\s+/);
       var maxWords = 2; 
       var numWords = words.length;
       if(numWords > maxWords){
    		  jobValue.preventDefault(); 
        }
}
<input type="text" id="wordIntent" onkeydown="wordLimit()" > 

Upvotes: 5

Views: 15852

Answers (4)

Tommy Cunningham
Tommy Cunningham

Reputation: 120

Here is a flexible script for restricting the words allowed for an input/textarea I have created, this function allows you to add the onkeyup event to any input/textarea to limit the words allowed for it.

JavaScript:

function wordLimit(inp, limit){
    var val = inp.value
    var words = val.split(/\s+/);
    var legal = "";
    for(i = 0; i < words.length; i++) {
        if(i < limit) {
            legal += words[i] + " ";
        }
        if(i >= limit) {
            inp.value = legal.trim();
        }
    }
}

HTML:

<input type="text" name="two-words" onkeyup="wordLimit(this, 2);">
<textarea name="ten-words" onkeyup="wordLimit(this, 10);"></textarea>

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65796

You can just get the value of the textbox and then split that into an array where there are spaces and then check how many items are in the array:

// Add event handler for event that can be cancelled and prevent excessive data
// from ever getting into the textbox
document.getElementById("input").addEventListener("keypress", function(evt){

  // Get value of textbox and split into array where there is one or more continous spaces
  var words = this.value.split(/\s+/);
  var numWords = words.length;    // Get # of words in array
  var maxWords = 2;
  
  // If we are at the limit and the key pressed wasn't BACKSPACE or DELETE,
  // don't allow any more input
  if(numWords > maxWords){
    evt.preventDefault(); // Cancel event
  }
});
<input type="text" id="input">

Upvotes: 7

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

You can add an eventlistener, then test the number of words.

  • Find all inputs that have a word limit
  • Iterate through each item in the list
  • Add an event listener to each item
  • Find the number of words in the input with onkeydown
  • If we have reached the max number of words don't allow for any more spaces
  • Otherwise we can allow for other characters

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

Upvotes: 13

wilburhimself
wilburhimself

Reputation: 26

You can use compare the maximum words allowed against the current words in the textarea.

To get the current words I suggest using a regular expression like:

currentWords = $('#textBox1').val().split(/[\s]+/);

And then check if the buttons pressed are the backspace or the delete buttons to allow the user to fix words.

Example:

var maxWords = 2, currentWords; // Maximum word length
$('#textBox1').keydown(function(e) {    
    currentWords = $('#textBox1').val().split(/[\s]+/);
    if (currentWords.length > maxWords) { 
        if ( e.keyCode == 46 || e.keyCode == 8 ) {// Allow backspace and delete buttons
    } else if (e.keyCode < 48 || e.keyCode > 57 ) {//all other buttons
        e.preventDefault();
    }
});

Upvotes: 0

Related Questions