Limit the number of words in an HTML input box

Is it possible to set a maximum word limit for a textbox that a user can input, rather than limiting the number of characters?
I did some research and discovered a way to determine the number of words a user has entered using regular expressions, but I'm unsure how to prevent them from entering more words once the limit is reached.

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

PS.
I want to restrict 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()" > 

Answer №1

To implement word limit functionality, you can add an event listener to each input field and monitor the number of words being entered.

  • Identify inputs with word limits
  • Iterate through the list of input fields
  • Attach an event listener to each input
  • Determine the word count using the onkeydown event
  • If the maximum word limit is reached, prevent further input of spaces
  • Allow input of other characters if the word limit has not been reached

// Select inputs with word limits
document.querySelectorAll('input[data-max-words]').forEach(input => {
  // Retrieve the word limit for the input
  let maxWords = parseInt(input.getAttribute('data-max-words') || 0)
  // Add event listener to monitor key inputs
  input.addEventListener('keydown', e => {
    let target = e.currentTarget
    // Calculate word count in the input
    let words = target.value.split(/\s+/).length
    // Prevent space input if word limit is exceeded
    if (!target.getAttribute('data-announce'))
      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>

Answer №2

To retrieve the content of the textbox, you can split it into an array based on spaces and then determine the number of items in the array:

// Creating an event handler for a cancelable event and preventing excessive data entry
// from being input into the textbox
document.getElementById("input").addEventListener("keypress", function(evt){

  // Splitting the textbox value into an array based on one or more continuous spaces
  var words = this.value.split(/\s+/);
  var numWords = words.length;    // Determining the number of words in the array
  var maxWords = 2;
  
  // If the word limit is reached and the key pressed is not BACKSPACE or DELETE,
  // restrict any further input
  if(numWords > maxWords){
    evt.preventDefault(); // Cancel the event
  }
});
<input type="text" id="input">

Answer №3

If you're looking for a useful script to control the words allowed in an input or textarea, I've got you covered. This function is flexible and lets you set limits on the words accepted for a given input or textarea.

Check out the JavaScript code below:

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();
        }
    }
}

And here's how you can implement it in your HTML:

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

Answer №4

To ensure that the number of words in a textarea does not exceed the specified limit, you can compare the maximum allowable words with the current words inputted.

One way to determine the current number of words is to utilize a regular expression like the following:

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

You can then monitor for the backspace or delete key presses to enable users to correct any errors in the input.

For instance, you can implement the following logic:

var maxWords = 5, currentWords; // Maximum number of words allowed
$('#inputArea').keydown(function(e) {    
    currentWords = $('#inputArea').val().split(/[\s]+/);
    if (currentWords.length > maxWords) { 
        if (e.keyCode == 46 || e.keyCode == 8) { // Allowing backspace and delete functionality
    } else if (e.keyCode < 48 || e.keyCode > 57) { // Disabling other key presses
        e.preventDefault();
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The mobile menu functions correctly on Jfiddle but is not functioning on the local server

I was working on a responsive mobile menu and used a toggleClass function to open the menu. It's functioning correctly in Jfiddle and below, but every time I click the nav icon in the live preview within brackets, nothing happens. I even tried it in a ...

Having trouble adding jQuery variable information through Ajax

When I click a certain button, I am attempting to insert a specific variable string "date" into my database. var date2 = curr_year + "-" + m_names[curr_month] + "-" + curr_date + "T" + curr_hour2 + ":" + curr_min + ":" + milli + " "; var date ...

Exploring the process of iterating through and organizing a JavaScript array

Recently, I encountered a JavaScript object that was generated by a particular API. The object is structured in a way that it can potentially have multiple instances of the same 'equity' (such as Hitachi Home in this case): { "results": { ...

What could be causing my JSON product list to not load properly?

My list is not loading and I can't figure out why. I've included my json, jquery, and HTML below. The console isn't showing any errors, but the list is still blank. Any help would be greatly appreciated as I am new to working with json. Than ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...

Arranging divs beneath other elements using CSS positioning without needing to modify the HTML code

i need to align the list elements under the menu items, but the layout crashes when the fourth item is displayed. I can't change the HTML code without affecting the layout of my app. Is there a way to dynamically hide and show the elements on the page ...

Error: The function row.child.hasClass is not a recognized function

My challenge is creating row details for DataTables without using Ajax. I have implemented something like this: $(document).ready(function () { function format ( name, value ) { return '<div>Name: ' + name + '<br /> ...

Angular static dropdown option

<input [formControl]="twitterHandle" id="twitterHandle" placeholder="twitterHandle"> Fetching the input value from the Twitter handle input field using the following code: twitterHandle = new FormControl(); this.twitterHandle.value; Similarly, if ...

Typescript does not produce unused members

Having an issue with the JS code that TypeScript compiler is generating. Here's an example class: // Class export class UserDTO { Id: number; FirstName: string; LastName: string; DateOfBirth: Date; getFullName(): string { ...

Different ways to swap table cells using only CSS

Does anyone know how to switch the positions of table cells using only CSS? I have three divs set up like this: #content { width: 1000px; display: table; float: none; vertical-align: top; border: 1px solid red; } #left { float: left; } #ri ...

Looking for assistance with troubleshooting CSS issues specifically in Internet Explorer

Hey there! I've been working on a landing page and it's looking good in Safari, Firefox, and Chrome. The only issue is that the layout is all messed up in IE (any version). If any of you experts could take a look at it and give me some suggesti ...

Is it possible to trigger the eventListener just once for every instance of my constructor?

I have a common property that is shared among all instances of my constructor: function Me() { } Me.prototype.window = {}; I want to update this property when the window is resized, but I only want it to happen once for each resize event, regardless of h ...

incorporating additional lines into the datatable with the help of jquery

I am attempting to directly add rows to the datatable by assigning values in the .js file through the Metronic theme. However, despite displaying item values during debugging, the values are not being added to the datatable row array and thus not reflect ...

The created function in VueJS may sometimes result in an undefined outcome

I recently started a project with VueJs where I encountered an issue while making a GET request using the Axios library. The data was returned as expected, but I faced difficulties calling the loadUsers function inside mounted. Here is my code snippet: ex ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

Safari compatible JavaScript needed for enforcing required fields in HTML5

I have been using the following script to adjust the HTML5 required attribute of my input elements. However, I am now looking for a way to tweak this script so that it can also function properly in Safari browsers, where support for this attribute may be l ...

Exploring the versatility of Angular 4 by implementing a switch feature with

My goal is to have the menu change based on the click of the "Cadastros" action, but it seems like the issue lies with the "workspaceSelected" property not being visible to all components. I believe the best approach in this situation would be to have the ...

What is the best way to delete a div element from a list

Check out the following code snippet. <div id="list"> <div class="a">1</div><div class="b">1</div></div> <div id="list"> <div class="a">2</div><div class="b">2</div></div> <div id= ...

Returning a JSON representation of a JavaScript object

In the process of working on a script, I encountered a situation where an $.ajax call had to invoke a function upon success, returning a JavaScript object in JSON format [object object]. However, despite being able to return a well-formatted string, access ...

The placement of an element is determined by its size and proportions

I'm experiencing some issues with avatars on my website. When the avatar size is set to 35x35 pixels, everything works fine. However, problems arise when the dimensions exceed 35x35 pixels. I suspect that the problem is related to the "position: abso ...