Web Development => JavaScript => Topic started by: on 9 Dec 2020, 05:35:22 pm

Title: Limit how many words can be entered into an input
Post by: on 9 Dec 2020, 05:35:22 pm
I'd like to use this little keyword function, the problem is I want to limit how many keywords can be entered. Adding maxlength="10" to the input doesn't do it. It limits how many characters can be entered, but not how many keywords.
Title: Re: Limit how many words can be entered into an input
Post by: coothead on 9 Dec 2020, 09:14:46 pm
Hi there,

my javascript skills are rather amateurish but
this example does limit the word count to a
defined value...

Code: [Select]
<html lang="en">

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>word count</title>

The internal CSS should be transferred to an external file
<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
body {
    background-color: #f0f0f0;
    font: normal 1em / 1.62em sans-serif;
#words {
width: 100%;
box-sizing: border-box;


<input id="words" type="text">

(function( d ) {
   'use strict';
   var ary = [], keypresses = 0, spacecount = 0, wordcount = 10,
       words = d.getElementById( 'words');
       words.addEventListener( 'keypress',
        function(e) {
           ary.push( e.code );
              if ( keypresses-1 !== -1  &&
                 e.code === 'Space' &&
                 ary[keypresses-1] !== 'Space' ) {
             spacecount ++;
              if ( spacecount >= wordcount ) {
             words.disabled = true;
          keypresses ++;
}( document ));


Title: Re: Limit how many words can be entered into an input
Post by: Jason Knight on 10 Dec 2020, 05:02:18 am
Wrong forum area :P

Code: [Select]
<input type="text" pattern="^(\s*\b\S+\b\s*){0,10}$">

Note, if this is "keywords" as in the meta, you should limit to 8, not 10.

This is also a case where placeholder makes sense.

Code: [Select]
Restricted Input Test
placeholder="zero to eight single words"
title="This field should have zero to eight single words separated by spaces inside it."

fun tip, title is shown in the error popup.

This has not been JavaScript's job -- at least in modern browsers -- for about a decade.

That said, yeah... regex suck to work with.

-- edit -- oh and don't forget, you STILL have to check this server-side. Client side checks can NEVER be trusted. They are a convenience for the user, NOT actual validation.