Solved

Add javascript to a textarea

Posted on 2006-10-19
14
533 Views
Last Modified: 2011-09-20
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?
0
Comment
Question by:scottspivey
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
14 Comments
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 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
0
 
LVL 1

Author Comment

by:scottspivey
ID: 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>
0
 
LVL 5

Expert Comment

by:aaronchan
ID: 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>
0
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
LVL 23

Expert Comment

by:rama_krishna580
ID: 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
0
 
LVL 18

Expert Comment

by:Morcalavin
ID: 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>
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 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;
  }
}
0
 
LVL 1

Author Comment

by:scottspivey
ID: 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>

0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 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">
0
 
LVL 1

Author Comment

by:scottspivey
ID: 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
0
 
LVL 1

Author Comment

by:scottspivey
ID: 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.
0
 
LVL 1

Author Comment

by:scottspivey
ID: 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.
0
 
LVL 54

Accepted Solution

by:
b0lsc0tt earned 500 total points
ID: 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.
0
 
LVL 1

Author Comment

by:scottspivey
ID: 17769381
b0lsc0tt,

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

thx,

scott
0
 
LVL 54

Expert Comment

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

bol
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question