Website Design Edmonton       Website Design Feedback       Website Design Sitemap     Contact Website Design Company
Website Designers R Us - Home
Restricting visitor input from a text box HTML TEXTAREA element

Your forms might have text boxes (created using the <TEXTAREA> tag) through which you plan to collect some details from your visitors. Now, it's always better to restrict such input to a defined number of words. We don't want users to send us thousands of words, do we?

We'll employ the function we met in the last tip (Counting words entered in a text box) and modify it so that we receive only a defined number of words.
The function discards everything after the 30th word.

 

function count_words(tbox_input)
   {
   var msg = "";
   var c = 0;
   w = tbox_input.value.split(" ");
   no_words = w.length;
   for (x = 0; x < no_words; x++)
      {
      if (c >= 30)
         {
         alert("Only thiry words please!");
         tbox_input.value = msg;
         break;
         }
      msg = msg + w[x] + " ";
      c++;
      }
   return false;
   }

Two variables msg and c are initialized when the function is called. The entire value of the TEXTAREA element is split using split() method with the space character as a separator of words. The result is stored in an array w. The number of words is calculated with the length property. A for loop is then employed with which we add the first thirty elements of the array and store the result in variable msg. Variable c keeps a tab on the number of words being added to msg. At each iteration of the loop, the value of c is checked. If it is greater than 30 (our limit), we display an alert, assign TEXTAREA the value msg (the first thirty words) and break out of the loop.

The function above always returns false. You would have to change it to return false ONLY when the number of words is more than 30.

Here is how you do it:

function count_words(tbox_input)
   {
   var msg = "";
   var c = 0;
   var er = 0;
   w = tbox_input.value.split(" ");
   no_words = w.length;
   for (x = 0; x < no_words; x++)
      {
      if (c >= 30)
         {
         alert("Only thiry words please!");
         tbox_input.value = msg;
         er = 1;
         break;
         }
      msg = msg + w[x] + " ";
      c++;
      }
   if (er)
      {
      return false;
      }
   return true;
   }
Return to Listing

Website Designers R us is based in Canada with branch office in Los Angeles, California. We are website developer & designer and have already created many ecommerce website design for USA, UK, and European countries. Our website development & creation is based on proper tools and techniques considering search engine optimization of the website.
 Home          ::             About Us          ::             Support            ::             Services            ::             Link Partners          ::             Contact

Copyright © 2006-2011 Website Designers R Us, a DOT Specialist Company. All rights reserved.