Solved

Repeating onsubmit javascript for multiple text areas

Posted on 2013-01-18
21
558 Views
Last Modified: 2013-01-21
Hi,

I'm trying to add a maxlength validation for cftextarea in coldfusion.  I've tried using JQuery examples to add a maxlength to a coldfusion cftextarea; we have multiple javascripts that I think it breaks the jquery methods.  

What does work is the following javascript function below.  The problem is that I need more than one cftextarea validated per form, so I need to somehow modify the js so that the  javascript looks for a div or a class to assign a max length.  I don't know javascript that well yet, but think that this is fairly straight forward.  Any assistance would greatly be appreciated.
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function testlen(field,maxlen,msg,showval){
   /*
   Validates maxlength for a CFFORM CFTEXTAREA richtext field. 
   Created by Charlie Arehart, carehart.org, 8/1/2008
   - field (required): name of rich textarea field on form to validate (case sensitive!)
   - maxlen (required): the maximum length to be permitted for the length of the textarea body (including generated html)
   - msg (optional): a message to be shown to the user, or empty string ('') to show a default message defined as "defaultmsg" below
   - showval (option): if 'yes', will show the actual generated body as part of the message
   */
   var body = ColdFusion.getElementValue(field);
   var defaultmsg = 'The ' + field + ' field must be less than ' + maxlen + ' characters.'
   // test textarea body length    
   if (body.length > maxlen) {
      // if no message is passed in, create a default one (the onsubmit in cfform seems to require all args be passed, so 3rd arg can't be left out, but an be set to '')       
	  if (msg.length < 1) msg=defaultmsg;
      // show the current value, if requested       
	  if (showval == 'yes') msg=(msg + '\nCurrent value (with HTML) is:\n' + body)
	  
      alert(msg)
      return (false);
   }
}
//--> </SCRIPT>

<!--- note that for the cfform onsubmit, it appears you must specify all args of a called function --->
<cfform onsubmit="return testlen('description',10,'','yes')" >
Description (up to 10 characters, including HTML):
<cftextarea name="description" richtext="yes" toolbar="Basic" <!---onChange="return testlen('description',10,'','yes')"--->>12345</cftextarea>
<cftextarea name="description2" richtext="yes" toolbar="Basic" <!---onChange="return testlen('description2',10,'You cant do that','yes')"--->>12345</cftextarea>

<input type="Submit">
</cfform>

<cfif cgi.request_method is "post">
   <cfdump var="#form#">
</cfif>

Open in new window

0
Comment
Question by:atljarman
  • 9
  • 7
  • 3
  • +1
21 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38795935
Can you please show what the cftextarea renders as?

<textarea> or some kind of html editor?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38796293
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38796312
I found this page

http://forums.adobe.com/message/1020940

Which suggested using

ColdFusion.RichText.getEditorObject('your-textarea-id').GetHTML()
0
 

Author Comment

by:atljarman
ID: 38796436
So what I did was I tried to modifiy the onsubmit function in the form tag so that it would check two fields.  What happened though, is it returns the form if the lenght of the first form is within the set limits.  

Here are the javascripts created, the first in the head of the document the second within the body of the document:
<script type="text/javascript">/* <![CDATA[ */
	ColdFusion.Ajax.importTag('CFTEXTAREA');
/* ]]> */</script>

<script type="text/javascript">/* <![CDATA[ */
	_cf_richtext_init_1358594951799=function()
	{
		
		
		ColdFusion.RichText.initialize('cf_textarea1358594951798', 'description', '12345', '/CFIDE/scripts/ajax/FCKeditor/', null, null, null, null, null, null, false, 'Basic', null, null, 'en');
	};ColdFusion.Event.registerOnLoad(_cf_richtext_init_1358594951799);
/* ]]> */</script>

<script type="text/javascript">/* <![CDATA[ */
	_cf_richtext_init_1358594951801=function()
	{
		
		
		ColdFusion.RichText.initialize('cf_textarea1358594951800', 'description2', '12345', '/CFIDE/scripts/ajax/FCKeditor/', null, null, null, null, null, null, false, 'Basic', null, null, 'en');
	};ColdFusion.Event.registerOnLoad(_cf_richtext_init_1358594951801);
/* ]]> */</script>
<script type="text/javascript">
<!--
    _CF_checkCFForm_1 = function(_CF_this)
    {
        //reset on submit
        _CF_error_exists = false;
        _CF_error_messages = new Array();
        _CF_error_fields = new Object();
        _CF_FirstErrorField = null;


        //display error messages and return success
        if( _CF_error_exists )
        {
            if( _CF_error_messages.length > 0 )
            {
                // show alert() message
                _CF_onErrorAlert(_CF_error_messages);
                // set focus to first form error, if the field supports js focus().
                if( _CF_this[_CF_FirstErrorField].type == "text" )
                { _CF_this[_CF_FirstErrorField].focus(); }

            }
            return false;
        }else {
            // run userdefined onSubmit javascript. 
            return testlen('description',10,'','yes');return testlen('description2',10,'','yes')
            return true;
        }
    }
//-->
</script>



<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!--
function testlen(field,maxlen,msg,showval){
   /*
   Validates maxlength for a CFFORM CFTEXTAREA richtext field. 
   Created by Charlie Arehart, carehart.org, 8/1/2008
   - field (required): name of rich textarea field on form to validate (case sensitive!)
   - maxlen (required): the maximum length to be permitted for the length of the textarea body (including generated html)
   - msg (optional): a message to be shown to the user, or empty string ('') to show a default message defined as "defaultmsg" below
   - showval (option): if 'yes', will show the actual generated body as part of the message
   */
   var body = ColdFusion.getElementValue(field);
   var defaultmsg = 'The ' + field + ' field must be less than ' + maxlen + ' characters.'
   // test textarea body length    
   if (body.length > maxlen) {
      // if no message is passed in, create a default one (the onsubmit in cfform seems to require all args be passed, so 3rd arg can't be left out, but an be set to '')       
        if (msg.length < 1) msg=defaultmsg;
      // show the current value, if requested       
        if (showval == 'yes') msg=(msg + '\nCurrent value (with HTML) is:\n' + body)
        
      alert(msg)
      return (false);
   }
}
//--> </SCRIPT>

Open in new window


Here is the form that renders:
<form name="CFForm_1" id="CFForm_1" action="" method="post" onsubmit="return _CF_checkCFForm_1(this)">
Description (up to 10 characters, including HTML):
<textarea name="description"  id="cf_textarea1358594951798" >12345</textarea>
<textarea name="description2"  id="cf_textarea1358594951800" >12345</textarea>




<input type="Submit">
</form>

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38796486
I cannot believe it renders a normal textarea if you have rich text editor. But why have a rich text editor for 10 chars?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38796498
Ok

1) change

function testlen(field,maxlen,msg,showval){
   var body = ColdFusion.getElementValue(field);

to

function testlen(field,maxlen,msg,showval){
   var body = field.value;


and change

}else {
            // run userdefined onSubmit javascript. 
            return testlen('description',10,'','yes');return testlen('description2',10,'','yes')
            return true;
        }

Open in new window

to
}else {
            // run userdefined onSubmit javascript. 
           var areas = _CF_this["description"];
           if (!areas.length) areas = [areas]; // create array
           for (var i=0;i<areas.length;i++) {
              if (!testlen(areas[i],10,'','yes')) return false;
            }
            return true;
        }

Open in new window

0
 

Author Comment

by:atljarman
ID: 38796653
}else {
            // run userdefined onSubmit javascript.
            return testlen('description',10,'','yes');return testlen('description2',10,'','yes')
            return true;
        }

Is generated by coldfusion from the <cfform onsubmit="return testlen('description',10,'','yes');return testlen('description2',10,'','yes')" >  

While I see what your doing, should I just take the onsubmit off the cfform, then add the javascript directly in the file.  Also, while in the example it is set to 10 characters, I will need varying lenths of 1200, 1500, and 2500 characters.
0
 
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 150 total points
ID: 38796728
Just replace what you have now with what I posted. that should be ok.

If you need varying lengths you can change 10 to

area[i].getAttribute("maxlength")

Open in new window

0
 

Author Comment

by:atljarman
ID: 38796881
So I commented out the onsubmit in the form and added the javascript directly in the page, and it indicates that the object can not be found.  Any thoughts.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38797178
???

If the script you posted worked fo 1 field, then the amendment I suggested will work for more than one field.

I did not suggest you change the onsubmit. Why would you do that?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:atljarman
ID: 38797201
The first script block was autogenerated by Coldfusion. I will try your suggestion and see if I can get it to work as a textarea.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 38797409
Isn't this your handwritten code?

        // run userdefined onSubmit javascript.
            return testlen('description',10,'','yes');return testlen('description2',10,'','yes')
            return true;
0
 

Author Comment

by:atljarman
ID: 38797640
No.  Coldfusion adds that code with the cftextarea.  What I've coded in is the second set of javascript and the javascript in the cfform --->

<cfform onsubmit="return testlen(...">
    <cftextarea richtext="true" name="description"></cftextarea>
</cfform>

When the code renders, it adds the script.  I'm wondering if I can replace the generated script somehow and just make it a cftextarea without the onsubmit in the cfform.
0
 
LVL 52

Expert Comment

by:_agx_
ID: 38799814
altjarman:  I'm wondering if I can replace the generated script somehow
and just make it a cftextarea without the onsubmit in the cfform.

@altjarman - Unfortunately not.  The implementation of cftextarea is quirky IMO.  The article you linked in your other question explained why you can't use the usual CF specific methods like onValidate(..), etc..  If displaying the current HTML in the error message is a requirement, then you'll have to use onSubmit, or something similar.  If it's *not* a requirement, there may be a few CF specific "workarounds" ...


mplungjan: If the script you posted worked fo 1 field, then the amendment I
suggested will work for more than one field.

@mplungjan - Yeah it probably would with a normal textarea. But CFtextarea's have a few extra nuances.  

1) The current value of the textarea is stored with the editor. To get an accurate count, you cannot use "field.value". You must use:  

     
ColdFusion.getElementValue(fieldName);

Open in new window


2) The "maxLength" attribute has special meaning in CF forms. That value is not passed through to the html. So this will return null:

       
area[i].getAttribute("maxlength")

Open in new window

0
 

Author Comment

by:atljarman
ID: 38800717
Thanks _agx_ for helping to clarify.  mplugjan has been working hard to help me come up with a solution.  Based on what you are seeing, do you see a way to do this?  I think if I can add the multiple values in a reference to a javascript function in the onsubmit of a cfform header tag, I think that would work.   What it would need to do is set a default message, run through each field, check the maxlength reqired, if the lenth is too long add something like the name of the field (or create a value to display in the javascript on submit).  Then as the javascript loops through the fields it could add a tag (example filed1): "field1 (1500), field2 (1200), field3 (2500)" with a final popup message of:  You have exceeded the length of the following fields: field1 (1500), field2 (1200), field3 (2500).
0
 
LVL 52

Expert Comment

by:_agx_
ID: 38803483
I think if I can add the multiple values in a reference to a javascript function in the onsubmit of a cfform header tag, I think that would work.

I don't think you need to do all that. What mplugjan suggested should work with some tweaks for the CF specific stuff.

Just append an extra attribute to the textareas you want to validate. Name it  "maxSize" or whatever you want as long as that name isn't the same as one of the tag's CF attributes. Then use mplugjan's code to loop through all textarea's in the page. If it contains the "maxSize" attribute - validate it.   But instead of displaying a separate alert for each error, I'd append the errors to an array and show all error messages at once. That's a little less annoying than one alert for each error IMO.

Here's one way you could adapt mplugjan's code:

<script type="text/javascript">
	// Returns a message if the textarea value exceeds the maximum length
	// Otherwise returns an empty string
	function validateTextAreaLength(fieldName, maxLen){
	   var body = ColdFusion.getElementValue(fieldName);
	   var remainLen = maxLen - body.length;
	   if (remainLen < 0) {
   	  	  return 'The maximum length for ' + fieldName + ' is ('+ maxLen + ') characters (incuding HTML).\n'
   	  	  		+ 'The current value is ('+ Math.abs(remainLen) +') characters too long';
       }
       return '';
    }

	function checkTextAreas() {
		// get all textareas
  		var areas = document.getElementsByTagName('textarea');

		// validate textarea length
		var errors = new Array();
  		for (var i=0; i <areas.length; i++) {
  	 		var message = "";
  	 		var fieldName = areas[i].name;
  	 		var maxSize = areas[i].getAttribute("maxSize");

  	 		// only validate when "maxSize" attribute is present
  	 		if (maxSize > 0) {
  	 			message = validateTextAreaLength(fieldName, maxSize);
  	 				
  	 		}
  	 		// save error message
  	 		if (message.length > 0) {
  	 			errors.push(message);	
  	 		}
  	 	}
  	 	
  	 	//display any errors
  	 	if (errors.length > 0) {
  	 		alert( errors.join("\n\n"));
  	 		return false;	
  	 	}
  	 	
    	return true;
	}   
</script>

<cfform onsubmit="return checkTextAreas()" >
    <cftextarea name="description1" richtext="yes" toolbar="Basic" maxSize="20">12345</cftextarea>
     <cftextarea name="description2" richtext="yes" toolbar="Basic" maxSize="30">12345</cftextarea>
     <!--- this will NOT be validated because its missing the "maxSize" attribute --->
    <cftextarea name="description3" richtext="yes" toolbar="Basic">12345</cftextarea>

    <input type="Submit">
</cfform>

Open in new window

0
 

Author Comment

by:atljarman
ID: 38803516
_agx_, that is awesome.  Thank you both.  One question that I have, is that can you some how pull the label for the field?  It might be more helpful to people entering data to see the question prompt in the label and not the value of the name tag of the cftextarea?

I really really appreciate your guys help as I was going crazy with this one and need like 5-8 cftextareas on the same form.
0
 
LVL 52

Accepted Solution

by:
_agx_ earned 350 total points
ID: 38803542
>  I was going crazy with this one

No wonder. The ajax stuff is finicky, but they forgot some key features when integrating richtext fields, making basic validation harder than it should be. They really make you work for it, lol.

You could either add the user friendly label as an attribute of the textArea and extract it the same way as "maxSize". OR link the label "id" to the textArea name. Then extract the value dynamically:

<script type="text/javascript">
	// Returns a message if the textarea value exceeds the maximum length
	// Otherwise returns an empty string
	function validateTextAreaLength(fieldLabel, fieldName, maxLen){
       // this is a lazy non-standard hack to get element text
       // replace this with DOM standard syntax
       var label = document.getElementById(fieldLabel).innerHTML;
	   var body = ColdFusion.getElementValue(fieldName);
	   var remainLen = maxLen - body.length;
	   if (remainLen < 0) {
   	  	  return 'The maximum length for ' + label + ' is ('+ maxLen + ') characters (incuding HTML).\n'
   	  	  		+ 'The current value is ('+ Math.abs(remainLen) +') characters too long';
       }
       return '';
    }

	function checkTextAreas() {
		// get all textareas
  		var areas = document.getElementsByTagName('textarea');

		// validate textarea length
		var errors = new Array();
  		for (var i=0; i <areas.length; i++) {
  	 		var message = "";
  	 		var fieldName = areas[i].name;
  	 		var fieldLabel = fieldName +"_label";
  	 		var maxSize = areas[i].getAttribute("maxSize");

  	 		// only validate when "maxSize" attribute is present
  	 		if (maxSize > 0) {
  	 			message = validateTextAreaLength(fieldLabel, fieldName, maxSize);
  	 				
  	 		}
  	 		// save error message
  	 		if (message.length > 0) {
  	 			errors.push(message);	
  	 		}
  	 	}
  	 	
  	 	//display any errors
  	 	if (errors.length > 0) {
  	 		alert( errors.join("\n\n"));
  	 		return false;	
  	 	}
  	 	
    	return true;
	}   
</script>

<!--- note that for the cfform onsubmit, it appears you must specify all args of a called function --->
<cfform onsubmit="return checkTextAreas()" >
Description (up to 10 characters, including HTML):

<span id="description1_label">Product Description</span>
<cftextarea name="description1" richtext="yes" toolbar="Basic" maxSize="20">12345</cftextarea>
<span id="description2_label">Instructions</span>
<cftextarea name="description2" richtext="yes" toolbar="Basic" maxSize="30">12345</cftextarea>
<!--- this will NOT be validated because its missing the "maxSize" attribute --->
<cftextarea name="description3" richtext="yes" toolbar="Basic">12345</cftextarea>

<input type="Submit">
</cfform>

Open in new window

0
 

Author Closing Comment

by:atljarman
ID: 38803635
You guys did a great job.  _agx_ brought it home.  I really needed a fast solution and I'm glad you guys were able to help on a weekend.  I just wish I could increase the points beyond what is available.
0
 

Author Comment

by:atljarman
ID: 38803906
When I try to customize the toolbar:

function FCKeditor_OnComplete(editorInstance)
{
 editorInstance.Config["ToolbarSets"]["MyToolBar"] = [
 ['SpecialChar','Bold','Italic','Underline','Subscript','Superscript','SpellCheck','Link']
 ];
editorInstance.EditorWindow.parent.FCK.ToolbarSet.Load('MyToolBar' ) ;
}

It breaks the code.  Any thoughts?

I added this question as this is really a new question:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/Cold_Fusion_Markup_Language/Q_28003738.html
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

743 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now