Question

Add javascript to a textarea

Asked by: scottspivey

i need to add javascript to a textarea to display an error message if a user enters more than 2000 characters.  the process the user currently goes through is they type a message in the textarea and then they click on "add description."  if there are more than 2000 characters in the textarea when the user clicks "add description" i need the javascript to display an error message alerting the user that they have exceeded the maximum number of characters for the description.

any ideas on how i do this?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-10-19 at 10:10:19ID22030779
Tags

how

,

textarea

,

javascript

Topic

JavaScript

Participating Experts
4
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Set max characters in a textarea
    I have an ASP page with several textareas. I want to set a maximum of 255 characters for each textarea. How would I go about doing this since there doesn't seem to be a MaxLength property for the textarea?
  2. Textarea question????
    Hello How can I limit the input the number of caracters or lines in a textarea? And also, How can I count' the lines and caracters of a textarea. What I want to do is only to limit the editible area to the visible area of the textarea. Input tag isn't a solution because I...
  3. TextArea
    Hi, I am currently creating a webpage which will contain about twenty textarea which when scrolled will animate the text inside the box. The first page that I have created makes use of simple text boxes with no javascript and the user is required to scroll to animate the text...
  4. TEXTAREA
    Hi friends, Again, I am not if this question is most appropriate to ASP experts or JS experts! Please, see the website: http://www.comp.lancs.ac.uk/computing/research/ucrel/claws/trial.html I would like create in MY WEBSITE a script for doing two things: 1. Send the resul...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: b0lsc0ttPosted on 2006-10-19 at 10:17:53ID: 17767717

scottspivey,

Provide the textarea tag with an id attribute, if one doesn't already exist.  Then you can use the code below.

function checkMsg() {
var textArea = document.getElementById("textareaID");
  if (textArea.length > 2000) {
    alert("Your message is too long.");
  }
}

Call the function using the onclick event in the button (e.g. onclick="checkMsg(); return false;").

Let me know if you have any questions or need more information.

b0lsc0tt

 

by: scottspiveyPosted on 2006-10-19 at 10:23:53ID: 17767762

forgive me for this question but i am trying to get this done in the absence of my developer.  based on the code below my "testareaID" if "Form1", right?  and for the onclick event, how do i add that into the onclick event we are already using?

<tr>
      <td id="col3">
      <font size="4" color="#DD0000">Other Shares Description</font>
      <h5>&nbsp</h5>
      Your description is limited to 2000 characters.
      <form name=Form1 action=AddOtherShareText.asp method=post ID="Form1">
            <textarea name=txtMessage cols=75 rows=6><%=Request.Querystring("str")%></textarea>
            <br>
            <input type=submit name=btnSubmit value="Add Description" ID="Submit1">
            <!--onclick="window.opener.setMessage(document.Form1.txtMessage.value);window.close();"-->
            <input type=button onclick="window.close();" value="Cancel" ID="Button1" NAME="Button1">
            <p></p>
      </form>
      </td>
</tr>

 

by: aaronchanPosted on 2006-10-19 at 10:24:39ID: 17767768

<html>
<head><title>Validation Form</title>
</head>

<script language="JavaScript">
      function checkTxtLength(txt_elem, max_length) {
            if (txt_elem.value.length > max_length) {
                  alert('Text limit of ' + max_length + ' exceeded. Current: ' + txt_elem.value.length);
            }
      }
</script>
<body>
      <textarea id="txt" style="border: 1px solid black; width: 400px; height 200px;"></textarea>
      <br/>
      <input type="button" style="border: 1px solid black;" value="Add Description" onclick="checkTxtLength(document.getElementById('txt'), 2000);" />
</body>

 

by: rama_krishna580Posted on 2006-10-19 at 10:33:21ID: 17767853

Hi,

look at here...
http://javascript.internet.com/forms/limit-textarea.html

<HEAD>

<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else
countfield.value = maxlimit - field.value.length;
}
// End -->
</script>
</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<!-- textCounter() parameters are:  text field, the count field, max length -->

<center>
<form name=myform action="YOUR-SCRIPT.CGI">
<font size="1" face="arial, helvetica, sans-serif"> ( You may enter up to 125 characters. )<br>
<textarea name=message wrap=physical cols=28 rows=4 onKeyDown="textCounter(this.form.message,this.form.remLen,125);" onKeyUp="textCounter(this.form.message,this.form.remLen,125);"></textarea>
<br>
<input readonly type=text name=remLen size=3 maxlength=3 value="125"> characters left</font>
</form>
</center>

R.K

 

by: MorcalavinPosted on 2006-10-19 at 10:36:51ID: 17767883

Or you can do it dynamically as well as add a static check:
<script>
function countWords(element) {
      total = 20;
      if(element.value.length > total) {
            element.value = element.value.substring(0, 20);
      }
      document.getElementById('length').innerHTML = total - element.value.length;

}
</script>
<span id="length">20</span> characters left.<br/>
<textarea id="text" onkeydown="countWords(this)" onkeyup="countWords(this)"></textarea>

 

by: b0lsc0ttPosted on 2006-10-19 at 10:48:41ID: 17767981

Form1 is the id for the form tag.  You would need to assing an id to the textarea tag.  I used your code in the example below.  The submit button would get the onclick event since it is the "Description."  I used the same name for id that you used for name in the textarea so change "textAreaID" in my function to "txtMessage".

     <form name=Form1 action=AddOtherShareText.asp method=post ID="Form1">
          <textarea name=txtMessage id="txtMessage" cols=75 rows=6><%=Request.Querystring("str")%></textarea>
          <br>
          <input type=submit name=btnSubmit onclick="checkMsg();" value="Add Description" ID="Submit1">

I corrected my function so the new code is below ...

function checkMsg() {
var textArea = document.getElementById("txtMessage");
  if (textArea.length > 2000) {
    alert("Your message is too long.");
    return false;
  } else {
    return true;
  }
}

 

by: scottspiveyPosted on 2006-10-19 at 11:12:31ID: 17768201

b0lsc0tt,

something is missing or i did something wrong.  when i added your function and changed the textarea i can still add more than 2000 characters to the text area and i don't get an error message when i click on "add description".  when i after i click on "add description" the windows closes like before, but when i try to click on my link to open this page back up with the description i get an error message:

The system cannot find the file specified.

i know the file is there cause i went to it to begin with and i am looking at the server.  here is all of the code so you can see if i did something wrong or if there is something in the code that i should have mentioned.

<%@ Language=VBScript %>
<% If Request.Form("btnSubmit")="Add Description" then
      Response.Write "<script langauge=javascript>window.opener.setDesc(""" & Replace(Request.Form("txtMessage"), vbCrLF, "<br>") & """);window.close();</script>"
   end if
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en">
<head>
<title>Prospectus Central, LLC - Search</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<style type="text/css" media="all">#search{background-position:0 -21px}</style>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="/script.js" type="text/javascript" charset="ISO-8859-1">
</script>
<script language=javascript>
      function checkMsg()
            {
                  var textArea = document.getElementById("txtMessage");
                    if (textArea.length > 2000)
                  {
                        alert("Your description is too long. You must limit your description to 2000 characters.");
                        return false;
                  }
            
                  else
      
                  {
                        return true;
                  }
            }
</script>

</head>
<body>
<div id="main" style="width: 500px" align="center">
      <!-- #include virtual="/include.asp"-->
      <table cellpadding="0" cellspacing="0" ID="Table1">
      <tr>
            <td id="col3">
            <font size="4" color="#DD0000">Other Shares Description</font>
            <h5>&nbsp</h5>
            Your description is limited to 2000 characters.
            <form name=Form1 action=AddOtherShareText.asp method=post ID="Form1">
                  <textarea name=txtMessage id="txtMessage" cols=75 rows=6><%=Request.Querystring("str")%></textarea>
                  <br>
                  <input type=submit name=btnSubmit onclick="checkMsg();" value="Add Description" ID="Submit1">
                  <!--onclick="window.opener.setMessage(document.Form1.txtMessage.value);window.close();"-->
                  <input type=button onclick="window.close();" value="Cancel" ID="Button1" NAME="Button1">
                  <p></p>
            </form>
            </td>
      </tr>
      </table>
</div>
</body>
</html>

 

by: b0lsc0ttPosted on 2006-10-19 at 11:49:34ID: 17768541

I hope that the problem is caused by simple mistake I made in the submit input tag.  Try adding return in front of the function call like in the example below.

               <input type=submit name=btnSubmit onclick="return checkMsg();" value="Add Description" ID="Submit1">

 

by: scottspiveyPosted on 2006-10-19 at 11:57:29ID: 17768613

ok now i am getting a javascript error when i click on "add description".

Line: 1
Char: 279
Error: Expected ')'
Code: 0
URL: http://staging.prospectuscentral.com/AddOtherShareText.asp

 

by: scottspiveyPosted on 2006-10-19 at 12:02:17ID: 17768647

that error may have been caused by some of the symbols in the text that i typed.  i retyped the text without symbols and i don't get that javascript error, but i am getting the same error as i posted above.  i am doing to more testing to see what is causing that error.

 

by: scottspiveyPosted on 2006-10-19 at 12:23:27ID: 17768816

b0lsc0tt,

so far all i have figured out is that if i copy the description from a word document and paste it into this text area i get the error message when i try to revisit the page.

but if i copy 2000 characters from notepad and paste it into the text area i am able to click on "add description" and then revisit the page without any error message.  but the error message is not being displayed.  after i pasted the 2000 characters from notepad into the textarea i typed a sentence after it.  when i clicked on "add description" i did not get an error message.  when i open the "add description" box back up all of the 2000 characters are there and "12" of the characters i typed are left.  everything after that is truncated but no error message is displayed.

 

by: b0lsc0ttPosted on 2006-10-19 at 13:21:43ID: 17769322

I did find another error in the code I provided.  The first line in the function that sets the variable textArea should be getting the value.  Please use the line below instead.

var textArea = document.getElementById("txtMessage").value;

I did actually make a test of the code with the correction and it works fine for me now.  Let me know how this works or if you have any questions.

 

by: scottspiveyPosted on 2006-10-19 at 13:27:41ID: 17769381

b0lsc0tt,

perfect.  this works exactly the way i need it to now.

thx,

scott

 

by: b0lsc0ttPosted on 2006-10-19 at 13:35:49ID: 17769452

Your welcome!  I'm glad that I could help.  Thank you for the grade, the points and the fun question.

bol

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...