How to dynamically add new field in frontend

lansman 16 Jul, 2009
Hello,

I searched in all pages and didn't find that question..

How to create a button or a link that will call a function to add a new field (or 2)
let these 2 fields be added in the middle of the form every time you press the button ?

Thank you very much for this great component.
Max_admin 16 Jul, 2009
Hi,

you may load mootools and use the
new Element
and
injectAfter
to do this easily! I'm sure some examples are available everywhere online, here is some example from Chronoforms core:

create a new div and a span:
var divcontainer = new Element('div', {'class': 'fields_order', 'id':'fields_order_new'}).setStyle('background-color', '#116600');
var span_field_name = new Element('span', {'class': 'fields_order_text'});

inject span inside div:
span_field_name.injectInside(divcontainer);


Cheers
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
Max_admin 17 Jul, 2009
you can do it with clones, show me your js code and html code, no need to paste all your code here if its huge, just the pieces we are checking so its easy for us!

Regards
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
lansman 17 Jul, 2009
Hi,
Here is the script:
<script language="javascript" src="../_java/mootools-1.2.1-core-yc.js"></script> 
<script language="javascript" src="../_java/mootools-1.2-more.js"></script> 
<script language="javascript"> 
	<!--
	window.addEvent('domready', function() {
		$$('input.bt_plus').each(function(el) {
			el.addEvent('click', addRow);
		});
	});
	
	// IDs of the elements that will be cloned (excluding the id that is incremented, ie: input_1, input_2. The last number should not be included.)
	// They also need to be in the correct order!!
	var ids = new Array();
	ids[0] = 'input_';
	ids[1] = 'input2_';
	
	function delRow(el) {
		// destroying element
		this.getParent().destroy();
	}
	
	function addRow() {
		// ID of div element that was clicked, with 'div_' removed
		clickID = parseInt(this.getParent().get('id').replace('div_',''));
		// Generate ID of element to be created
		newID = (clickID+1);
		// Creating and adding new element
		newClone = $('div_'+clickID).clone().injectAfter('div_'+clickID);
		// Setting new div's element id
		newClone.set('id', 'div_'+newID)
		// Making sure the new field does not have a value carried from clone
		//newClone.getFirst('input').set('value', '');
		// Setting new input text id
		//newClone.getFirst('input').set('id', 'input_'+newID);
		// Adding click event on button, it will call addRow function
		//newClone.getFirst('input').getNext('input').addEvent('click', addRow);
			
		newClone.getChildren().each(function(item, index) {
 
			inputID = ids[index]+newID;
 
			if(item.get('type') == 'button') {
				item.addEvent('click', addRow);
			} else {
				item.set('value', '');
				item.set('id', inputID);
			}
		});	
		
		// Changing value of the button that was clicked
		this.set('value', '-');
		// removing current event that is used to addrow
		this.removeEvent('click', addRow);
		// adding event to remove row
		this.addEvent('click', delRow);
	}
	-->
</script> 


and this is the form:
<form name="myForm" action="mootools_row_clone_post_v2.php" method="post"> 
	<div id="input_container" style="padding:10px;"> 
  	Example: You can add/delete input fields since you don't kow how many your users will need.
    <br /> 
    After submitting you will see the resulting array from PHP
  	<div id="div_1"><input type="text" name="my_input[]" id="input_1" size="30" maxlength="30" /> <input type="text" name="my_input2[]" id="input2_1" size="30" maxlength="30" /> <input class="bt_plus" type="button" value="+" /></div> 
	</div> 
  <div style="padding:10px;"><input type="submit" value="Submit" /></div> 
</form> 


Thank you very much.

another question, if it can work, how can the additional fields be added to the mail template ?
lansman 17 Jul, 2009
In fact I have an even better script, and very simple to understand.
yet the add more fields doesn't work either.
please look at this one:

Script:
var counter = 0;

function moreFields() {
	counter++;
	var newFields = document.getElementById('readroot').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	for (var i=0;i<newField.length;i++) {
		var theName = newField[i].name
		if (theName)
			newField[i].name = theName + counter;
	}
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

window.onload = moreFields;


HTML:
<div id="readroot" style="display: none">

	<input type="button" value="Remove review"
		onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />

	<input name="cd" value="title" />

	<select name="rankingsel">
		<option>Rating</option>
		<option value="excellent">Excellent</option>
		<option value="good">Good</option>
		<option value="ok">OK</option>
		<option value="poor">Poor</option>
		<option value="bad">Bad</option>
	</select><br /><br />

	<textarea rows="5" cols="20" name="review">Short review</textarea>
	<br />Radio buttons included to test them in Explorer:<br />
	<input type="radio" name="something" value="test1" />Test 1<br />
	<input type="radio" name="something" value="test2" />Test 2

</div>

<form method="post" action="/cgi-bin/show_params.cgi">

	<span id="writeroot"></span>

	<input type="button" id="moreFields" value="Give me more fields!" />
	<input type="submit" value="Send form" />

</form>


This is a much better choice as it can simply add container of fields.
Please help me to get it working.
Thanks!
lansman 17 Jul, 2009
I'm really sorry I keep posting and answering myself, but i make progress and it might help others...

so eventually i put this script :
<script type="text/javascript">
var counter = 0;

function moreFields() {
	counter++;
	var newFields = document.getElementById('readroot').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	for (var i=0;i<newField.length;i++) {
		var theName = newField[i].name
		if (theName)
			newField[i].name = theName + counter;
	}
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

//window.onload = moreFields;

</script>


and add this to the form HTML:

<!-- start hidden box -->
<div id="readroot" style="display: none">
	<div class="form_item">
      <div class="form_element cf_textbox">
        <label class="cf_label" style="width: 150px;">Product:<span class="star-red">*</span>:</label>
        <input maxlength="150" size="30" title="" id="" name="" 	type="text" /> 

  
  </div>
  <div class="form_element cf_textarea">
    <label class="cf_label" style="width: 150px;">Price:</label>
    <textarea class="cf_inputbox" rows="2" id="text_12" title="Please add specific details" cols="24" name="notesurl_1"></textarea>
    
</div>
</div><input type="button" value="Remove Product"
		onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
</div>

<!--end of hidden box -->
<!-- start form -->
<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 150px;">Product:</label>
    <input maxlength="150" size="30" title="" id="text_4" name="url_1" type="text" />
      
  </div>
  <div class="form_element cf_textarea">
    <label class="cf_label" style="width: 150px;">Price:</label>
    <textarea rows="2" id="text_12" title="Please add specific details" cols="24" name="notesurl_1"></textarea>
    
<div class="cfclear"> <img src="images/system/horizontal-line.png" width="438" height="1" /></div>
      <div class="cfclear"> </div>
</div>
</div>

<span id="writeroot"></span>
<input type="button"  value="Add Product"  onclick="moreFields()" />


Which works beautifully, it does add the fields I wanted, and can even close the field.
but how can i add them to the mail being sent ?

i didn't add an ID and NAME to the hidden field, I don't know how to keep them unique, so maybe this is the problem.
please help me to put those added elements to the output result mail.

Thank you.

EDIT: If I add a Name to the field, the last field i added is shown in the debug as being recognized, but the other fields aren't.
GreyHead 18 Jul, 2009
Hi Lansman,

Your code creates new names by adding the counter value - you should be able to do the same with the id.

Bob
lansman 18 Jul, 2009
Hey,

I tried to add the Id like this :

var counter = 0; // counter for naming the elements



function moreFields()

{

        counter++;

        var newFields = document.getElementById('readroot').cloneNode(true);

        newFields.id = '';

        newFields.style.display = 'block';

        var newField = newFields.childNodes;

        for (var i=0;i<newField.length;i++)

        {

  var theName = newField[i].name

  if(theName)

  {

  newField[i].name = theName + counter; /* we need the name for php processing $_POST later */

  newField[i].id = theName + counter; /* need an id for the javascript manipulation because there is no getElementByName() only Id*/

  }

        }

        var insertHere = document.getElementById('writeroot');

        insertHere.parentNode.insertBefore(newFields,insertHere);

}



But it still cannot be seen in the debug.
in the form i added the id attribute, i can't figure this out...
is it a problem with the id, or the name ?

Thank you.
lansman 18 Jul, 2009
I found out that if i remove the Div's that after the "readroot" Div it does write new names and pass it over to the mail.

(after removed : <div class="form_item"> and <div class="form_element cf_textbox"> from the HTML)
<div id="readroot" style="display: none">
	<div class="form_item">
      <div class="form_element cf_textbox"> 


But then 2 small problems arise:
1. the added fields are no longer arranged in an ordered container.
2. the changed name jump strange : when i check it in dreamweaver the field has the pattern :
field_a1 Field_b1
field_a2 field_b2
field_a3 field_b3

but when adding the code to the form component, it jumps like this:

field_a1 Field_b2
field_a4 field_b5
field_a7 field_b8

Do you have any thought to why it jump like this in under the component ?
and how do I make it work with the additional Div for the "container" look ?

Please help on this.
Thank you.

EDIT: I managed to style them via css.
Another problem is: when captcha is wrong, the fields are deleted, and the data won't restore back when adding them again.
any thoughts on that ?
angie_iu 24 Jul, 2009
Hi, I have the same problem, but I don't have you knowledge ...
I test you code for adding field and it works very well.
Did you understand how to email that added elements?
Could you please post your final code (script +html)?
I really thank you!
lansman 26 Jul, 2009
Well the whole thing works great in Firefox and Chrome but it fails under IE7\IE8.
over all the codes are:
in Script:
var counter = 0;

function moreFields() {
	counter++;
	var newFields = document.getElementById('readroot').cloneNode(true);
	newFields.id = '';
	newFields.style.display = 'block';
	var newField = newFields.childNodes;
	for (var i=0;i<newField.length;i++) {
		var theName = newField[i].name
		var theId = newField[i].id
		if (theName)
			newField[i].name = theName + counter;
             newField[i].id = theId + counter;
	}
	var insertHere = document.getElementById('writeroot');
	insertHere.parentNode.insertBefore(newFields,insertHere);
}

//window.onload = moreFields;

I have removed the ++from the counter and now it counts good.
for the form you should so something like:
<!-- start hidden box -->

<div id="readroot" style="display: none;">
	      
        <label class="cf_label" style="width: 150px; padding-left:32px;">player:</label>
        <input class="cf_inputbox"   maxlength="150" size="30" title="Please add the producd's URL" name="player-more" id="player-more" type="text" />
        
   <br />
  <div class="cfclear"> </div>
 		
    <label class="cf_label" style="width: 150px;padding-left:32px;">Team:</label>
    <input class="cf_inputbox" maxlength="150" size="30" title="Please add specific details" name="team-more" id="team-more" type="text">

<input class="img_x" title="Press to remove the product" type="button" style="color:#FF0000;font-size:18px;font-weight:bold;font-family:Tahoma, Vrinda, Myriad Web Pro;" 
value=" X "
	onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
        <br />
</div>
<!--end of hidden box -->

<div class="form_item">
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 150px;">Player:</label>
    <input class="cf_inputbox" maxlength="150" size="30" title="" name="player" id="player"  type="text" />
    </div>
 
  <div class="form_element cf_textbox">
    <label class="cf_label" style="width: 150px;">Team:</label>
    <input class="cf_inputbox" maxlength="150" size="30" title="" name="team" id="team"  type="text" />
  </div>
 
</div>
<br />
<span id="writeroot"></span>
<input type="button"  title="Press to add more products" style="color:#33CC00;font-size:22px;font-weight:bold;font-family:Tahoma, Vrinda, Myriad Web Pro;" value=" + "  onclick="moreFields()" />


and for the template you use something like:

<?php
if ( $posted['player-more1'] ) {
  echo '<div><span style="font-weight:bold">Player:</span> {player-more1}</div>';
}
if ( $posted['team-more1'] ) {
  echo '<div><span style="font-weight:bold">Team:</span> {team-more1}</div>';
}
if ( $posted['player-more2'] ) {
  echo '<div><span style="font-weight:bold">Player:</span> {player-more2}</div>';
}
if ( $posted['team-more2'] ) {
  echo '<div><span style="font-weight:bold">Team:</span> {team-more2}</div>';
}
?>


hope it will help some others here, took me some time to learn all this, but can someone please check it
and say why it doesn't work under IE7 \ IE8 ?

if i check the code not inside Chrono forms it works in IE7 \ IE8, but under Chrono form when pressing the "add more fields" button it shows😮bject doesn’t support this property or method - Javascript Error

EDIT: It says the error is in this part:
newField[i].id = theId + counter;

We must add an ID to the field for the template to work, but how to do it right ?
how to add the ID + counter without an error ?

Please advice.
thank you.
Max_admin 26 Jul, 2009
Hi Lansman,

this line:
    newField[i].id = theId + counter;


should be:
    newField[i].setProperty('id', theId + counter);


Regards
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
lansman 27 Jul, 2009
Dear Max

Sadly it didn't work... also in firefox now.

gave a
Message: Object doesn't support this property or method
Line: 94
Char: 25
Code: 0

which point to the line you changed.
any other idea ?
Thanks
Max_admin 28 Jul, 2009
Hi, please make sure mootools is loaded at this page, for example by enabling the validation or the "Load chronoforms files" option under general tab!

Regards
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
lansman 28 Jul, 2009
Hi Max,

Yes, Mootools is loaded on any of my pages.
and also the "Load Chronoforms CSS/JS Files?" was and is enabled.
I still get the javascript error.
If you have time to try the code... does it work for you on IE7 ?
the error only happen under Chrono forms.

Thank you.
lansman 29 Jul, 2009
Hi,

Really hope you can solve it, its my last bug preventing me from publishing my site...

thanks.
Max_admin 03 Aug, 2009
Hi Lansman,

Try to undo my last suggestion and make sure that mootools is NOT loaded in the page at all, sometimes pure JS code conflicts with mootools itself and nothing work!

Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
lansman 03 Aug, 2009
Hi,
Do you have a quick trick to disable mootools in one page only ?
I'm pretty sure my template need it to run...

EDIT: I have tried disabling mootools and it doesn't work in IE as well.
The template looses some functions as well so i need to use the Mootools...

maybe some problem with any line in my code ?
Max_admin 07 Aug, 2009
Hi Lansman,

I tried to make a mootools version of your code, here its:

var counter = 0;

function moreFields() {
   counter++;
   var newFields = $('readroot').clone();
   newFields.setProperty('id', '');
   newFields.setStyle('display', 'block');
   newFields.getChildren().each(function(newField){
      var theName = newField.getProperty('name');
      var theId = newField.getProperty('id');
      if (theName){
         newField.setProperty('name', theName + counter);
         newField.setProperty('id', theId + counter);
	  }
   });
   var insertHere = document.getElementById('writeroot');
   $('writeroot').Parent().injectBefore(newFields);
}


I didnt test it though, you may face bugs, use firebug to check any, and let me know!

Regards
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
marklandry 15 Sep, 2009

Hi,

you may load mootools and use the

new Element
and
injectAfter
to do this easily! I'm sure some examples are available everywhere online, here is some example from Chronoforms core:

create a new div and a span:
var divcontainer = new Element('div', {'class': 'fields_order', 'id':'fields_order_new'}).setStyle('background-color', '#116600');
var span_field_name = new Element('span', {'class': 'fields_order_text'});

inject span inside div:
span_field_name.injectInside(divcontainer);


Cheers
Max



Hi Max,
I've been through this post and tried the solution below but can't it to work. Was wondering if you could unpack this solution for me as it looks simpler, I'm just not at a place where I understand where to put everything. Maybe some examples?

Also - unrelated to this - I'm having trouble adding emails to my forms. When I try to add an email it won't save. Worked fine a few weeks ago and it's happening with two different sites (on the same server)

Anyway, thanx for your help

Mark
GreyHead 16 Sep, 2009
Hi Mark,

What do you actually want to do? It's easier to give an example with some code to work with.

I don't know why the email save doens't work. There are some general problems with saving form containing (some) PHP in the latest release but straight-forward forms shouldn't be effected.

Bob
angie_iu 23 Nov, 2009
Hi,
just a question please.
You said

and for the template you use something like:

Code: Select all
<?php
if ( $posted['player-more1'] ) {
echo '<div><span style="font-weight:bold">Player:</span> {player-more1}</div>';
}
if ( $posted['team-more1'] ) {
echo '<div><span style="font-weight:bold">Team:</span> {team-more1}</div>';
}
if ( $posted['player-more2'] ) {
echo '<div><span style="font-weight:bold">Player:</span> {player-more2}</div>';
}
if ( $posted['team-more2'] ) {
echo '<div><span style="font-weight:bold">Team:</span> {team-more2}</div>';
}
?>



but...where do you put this code??
In "autogenerated code" or in form code section?

Thank you so much
Angela
GreyHead 23 Nov, 2009
Hi Angie,

That code was used in the Email template.

Bob

PS To use HTML in the template you must turn the HTML editor off in the Email Setup Properties box.
axels 15 Jan, 2010
Hi!

Did anyone find a solution to this? I'm trying to achieve the same thing.

I tried the "mootools version" of the JS (mootools is loaded by Joomla) and get this error when clicking the add-button:

Object doesn't support this property or method



on the following line:

$('writeroot').Parent().injectBefore(newFields);


Here's the current test HTML:
<div class="clearfloat"> </div>
	<div id="readroot" style="display: none;">
    
  <div class="form_element">
	<input class="cf_inputbox_mini cf_mini1" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
	<input class="cf_inputbox_mini cf_mini2" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
	<input class="cf_inputbox_mini cf_mini3" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
	<input class="cf_inputbox_mini cf_mini4" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
	<input class="cf_inputbox_mini cf_mini5" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
	<input class="cf_inputbox_mini cf_mini6" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
	<input class="cf_inputbox_mini cf_mini7" maxlength="150" size="4" title="" id="text_7" name="merke" type="text" />
  </div>
  <div class="clearfloat"> </div></div>
  
  <span id="writeroot"></span>
  
    <div class="clearfloat"> </div>
  

<input type="button"  title="Press to add more products" style="color:#33CC00;font-size:22px;font-weight:bold;font-family:Tahoma, Vrinda, Myriad Web Pro;" value=" + "  onclick="moreFields()" />

  <div class="clearfloat"> </div>
GreyHead 15 Jan, 2010
Hi axel,

You may need to make sure that the 'writeroot' span has a clear Parent <div> ??

Bob
axels 16 Jan, 2010
Got it to work by changing the last JS line to:

insertHere.parentNode.insertBefore(newFields,insertHere);

Working on some small enhancements, will post all working code in a single post when ready🙂
axels 17 Jan, 2010
I've consolidated the code/suggestions from this thread, and also added some more features:

[list]
  • Deleted items no longer remains as blank blocks

  • Items slides in and out

  • The mail outputs data using a foreach looping through all the fields that were posted. This scales up to an infinite number of custom fields instead of checking only the first manually.
  • [/list]
    Requires MooTools from default Joomla config! =)

    Here's a howto:

    1. Add the Jacascript code

    This code will perform the adding/removing of rows.

    Add to Form code -> Form Javascript:

    var counter = 0;
    
    function addFormBlock() {
    	counter++;
    	var newBlockId ='newBlock' + counter;
    	var newFields = $('readroot').clone();
    	newFields.setProperty('id', 'newBlockId');
    	newFields.setStyle('display', 'none');
    	newFields.getChildren().each(function(newField){
    		var theName = newField.getProperty('name');
    		var theId = newField.getProperty('id');
    		if (theName){
    			newField.setProperty('name', theName + '[]');
    			newField.setProperty('id', theId + counter);
    		}
    	});
    	var insertHere = document.getElementById('writeroot');
    	
    	insertHere.parentNode.insertBefore(newFields,insertHere);   
    	var addFormBlockSlider = new Fx.Slide( newFields, { duration: 500 } );
    	addFormBlockSlider.hide();
    	newFields.setStyle('display', 'block');
    	addFormBlockSlider.slideIn();
    
    }
    
    function deleteFormBlock(obj) {
    	
    
    	var deleteFormBlockSlider = new Fx.Slide( obj, { duration: 500 } );
    	
    	deleteFormBlockSlider.slideOut().chain(function(){
    		obj.remove(obj);
    	});
    	
    }


    2. Add the form HTML

    This code will display the form inputs, add/remove buttons, and it contains the hidden block that will be displayed by the Javascript.

    Add to Form code -> Form HTML:

    <!--start first block (visible) -->
    
    <div class="form_item">
      <div class="form_element cf_textbox">
    		<label class="cf_label" style="float:left;">Player:</label>
    		<input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="player" id="player"  type="text" />
    		<label class="cf_label" style="float:left;padding-left:40px;">Team:</label>
    		<input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="team" id="team"  type="text" />
    	</div>
    	<div class="cfclear"> </div>
    </div>
    
    <!--end first block (visible) -->
    
    <!-- start hidden block -->
    
    <div id="readroot" style="display: none;">
    <div class="form_item">
    	<div class="form_element cf_textbox">
    		<label class="cf_label" style="float:left;">Player:</label>
    		<input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="player-more" name="player-more[]" type="text" />          
    		<label class="cf_label" style="float:left;padding-left:40px;">Team:</label>
    	    <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="team-more" name="team-more[]" type="text" />
        	<input class="img_x" title="Click to remove this player" type="button" style="color:#FF0000;font-size:14px;font-weight:bold;margin-left:40px;" value=" X " onclick="deleteFormBlock(this.parentNode.parentNode.parentNode.parentNode);" />
    	</div>
    	<div class="cfclear"> </div>
    </div>
    </div>
    
    <!--end of hidden block -->
    
    <!-- start placeholder for added blocks -->
    
    <span id="writeroot"></span>
    
    <!-- end placeholder for added blocks -->
    
    <div class="form_item">
    	<div class="form_element">
    		<input type="button"  title="Click to add a new player" style="color:#33CC00;font-size:14px;font-weight:bold;" value=" + "  onclick="addFormBlock()" />
    	</div>
    </div>
    
    <div class="form_item">
      <div class="form_element cf_button">
        <br /><br /><input value="Send!" name="button_13" type="submit" />
      </div>
    	<div class="cfclear"> </div>
    </div>


    3. Set ut email

    Set up or edit an email. Make sure HTML is enabled, and set "Use Template Editor" to NO. Remember to apply.

    4. Add the mail template

    This code will handle the submitted form and mail the results to you.

    Add to Emails Templates -> the template you made in last step:

    <p>The following form was submitted:</p>
    <table style="border:0;">
    <?php // first print the static (visible) row ?>
    <tr>
    <td><b>Player: </b></td>
    <td style="padding-right:30px;">{player}</td>
    <td><b>Team: </b></td>
    <td>{team}</td>
    </tr>
    <?php
    
    //get the arrays from POST
    $player_more = JRequest::getVar('player-more', null, 'post');
    $team_more = JRequest::getVar('team-more', null, 'post');
    
    //loop through the player array and print it and the corresponding team
    foreach ($player_more as $key=>$value) {
    
    	// skip the hidden "source" row
    	if ($key != 0) {
    		// quick hack: add a divider
    		print "\n\n" . '<tr><td colspan="4" style="height:5px;border-bottom: 1px solid gray;margin-bottom: 5px;"> </td></tr>';
    		// print the info!
    		print "\n" . '<tr><td><b>Player:   </b></td><td style="padding-right:30px;">' . $value . '</td><td><b>Team:   </b></td><td>' . $team_more[$key] . '</td></tr>';
    	}
    
    }
    
    ?>
    </table>


    5. Disable ChronoForms handling of arrays

    Since the fields are saved to an array that PHP needs to loop through in the mail template, you will need to set "ChronoForms handle my posted arrays" to NO under general options.

    6. Hopefully working!

    Hope this is useful🙂
    GreyHead 17 Jan, 2010
    Hi axels,

    Excellent, thank you.

    Bob

    PS Adding the JavaScript to the Form JavaSCript box (without the script tags) should insert it into the page head for you.
    tiekubd 12 Mar, 2010
    I followed all the steps. Nothing happens when i click on the + button.
    Tieku
    tiekubd 12 Mar, 2010
    how do i know i have MooTools from default Joomla config?
    tiekubd 12 Mar, 2010
    After i went to Validation --> Enable Validation = Yes, i was able to add/remove new lines.
    Why does the first new line (line2) appear out of line (to the right). like this:

    line1
    line2
    line3
    line4
    line5

    Why is that when i set Enable Data Storage to yes i get an HTTP 500 error in my browser? i want to store the form results in a database.

    Any help appreciated.
    Ps Tieku
    GreyHead 12 Mar, 2010
    Hi Tieku,

    Enabling Validation had ChronoForms load the MooTools library for you. You can also do that with the Load ChronoForms script/CSS files on the for General tab.

    Line 2 looks to be perfectly in line here.

    The data storage error is probably because you have an invalid input name somewhere in your form.

    Bob
    tiekubd 13 Mar, 2010
    This is what line2 looks like:

    line1
    _____________line2
    line3
    line4
    line5

    How do i take a screen-shot and paste an image?

    "invalid input name"? Would that be a field name?
    tiekubd 13 Mar, 2010
    When i chose "Load ChronoForms script/CSS files on the for General tab" it fixed the alignment problem.
    tiekubd 13 Mar, 2010
    I copied the code below into the Form code. Which line would be the "invalid input name"

        <!--start first block (visible) -->
    
        <div class="form_item">
          <div class="form_element cf_textbox">
              <label class="cf_label" style="float:left;">Player:</label>
              <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="player" id="player"  type="text" />
              <label class="cf_label" style="float:left;padding-left:40px;">Team:</label>
              <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="team" id="team"  type="text" />
           </div>
           <div class="cfclear"> </div>
        </div>
    
        <!--end first block (visible) -->
    
        <!-- start hidden block -->
    
        <div id="readroot" style="display: none;">
        <div class="form_item">
           <div class="form_element cf_textbox">
              <label class="cf_label" style="float:left;">Player:</label>
              <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="player-more" name="player-more[]" type="text" />         
              <label class="cf_label" style="float:left;padding-left:40px;">Team:</label>
               <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="team-more" name="team-more[]" type="text" />
               <input class="img_x" title="Click to remove this player" type="button" style="color:#FF0000;font-size:14px;font-weight:bold;margin-left:40px;" value=" X " onclick="deleteFormBlock(this.parentNode.parentNode.parentNode.parentNode);" />
           </div>
           <div class="cfclear"> </div>
        </div>
        </div>
    
        <!--end of hidden block -->
    
        <!-- start placeholder for added blocks -->
    
        <span id="writeroot"></span>
    
        <!-- end placeholder for added blocks -->
    
        <div class="form_item">
           <div class="form_element">
              <input type="button"  title="Click to add a new player" style="color:#33CC00;font-size:14px;font-weight:bold;" value=" + "  onclick="addFormBlock()" />
           </div>
        </div>
    
        <div class="form_item">
          <div class="form_element cf_button">
            <br /><br /><input value="Send!" name="button_13" type="submit" />
          </div>
           <div class="cfclear"> </div>
        </div>
    GreyHead 13 Mar, 2010
    Hi Tieku,

    Any name with a dash in it like player-more[], use player_more[] instead.

    Bob
    tiekubd 13 Mar, 2010
    OK let me try that...
    tiekubd 13 Mar, 2010
    Bob,
    that worked. however when i click on submit i get the message "
    You are not allowed to access this URL". Do you know where this message is from?
    tiekubd 13 Mar, 2010
    Never mind the last message.
    tiekubd 13 Mar, 2010
    i have "Email the results ?" set to "Yes", i wonder why i am not getting emails?
    when i go to tables manager, record, the player and team fields are populated but the player_more and team_more fields are empty? and i clicked to create 4 records, where will the additional fields go. i thought an array was being generated?
    materiaweb 16 Mar, 2010
    Hi there,
    I made all the steps and it works like a charme, but...
    I try to have 2 different blocks of user added fields on the same form.
    And I managed to do it duplicating the function addFormBlock(), calling he 2 functions differently in relation to the block they apply to, then made all the necessary changes in variables names, both in HTML and Javascript.
    The email I receive as a result of my form is unbelievably OK except for the second block.
    I can see only the fixed fields and not the inputs for the user added fields.

    my Javascript now looks like this:
    
    var counter = 0;
    
    function addFormBlockAlbum() {
       counter++;
       var newBlockId ='newBlock' + counter;
       var newFields = $('readrootAlbum').clone();
       newFields.setProperty('id', 'newBlockId');
       newFields.setStyle('display', 'none');
       newFields.getChildren().each(function(newField){
          var theName = newField.getProperty('name');
          var theId = newField.getProperty('id');
          if (theName){
             newField.setProperty('name', theName + '[]');
             newField.setProperty('id', theId + counter);
          }
       });
       var insertHere = document.getElementById('writerootAlbum');
       
       insertHere.parentNode.insertBefore(newFields,insertHere);   
       var addFormBlockSlider = new Fx.Slide( newFields, { duration: 500 } );
       addFormBlockSlider.hide();
       newFields.setStyle('display', 'block');
       addFormBlockSlider.slideIn();
    
    }
    
    function addFormBlockStampa() {
       counter++;
       var newBlockId ='newBlock' + counter;
       var newFields = $('readrootStampa').clone();
       newFields.setProperty('id', 'newBlockId');
       newFields.setStyle('display', 'none');
       newFields.getChildren().each(function(newField){
          var theName = newField.getProperty('name');
          var theId = newField.getProperty('id');
          if (theName){
             newField.setProperty('name', theName + '[]');
             newField.setProperty('id', theId + counter);
          }
       });
       var insertHere = document.getElementById('writerootStampa');
       
       insertHere.parentNode.insertBefore(newFields,insertHere);   
       var addFormBlockSlider = new Fx.Slide( newFields, { duration: 500 } );
       addFormBlockSlider.hide();
       newFields.setStyle('display', 'block');
       addFormBlockSlider.slideIn();
    
    }
    
    function deleteFormBlock(obj) {
       
    
       var deleteFormBlockSlider = new Fx.Slide( obj, { duration: 500 } );
       
       deleteFormBlockSlider.slideOut().chain(function(){
          obj.remove(obj);
       });
       
    }
    

    My HTML form looks like this (displaying only the interesting part of it of course...)
    <!-- inizio blocco Album -->
    
    <!--start first block (visible) -->
    
    <div class="form_item">
      <div class="form_element cf_textbox">
          <label class="cf_label" style="float:left;">Titolo</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="titoloalbum" id="titoloalbum"  type="text" />
          <label class="cf_label" style="float:left;padding-left:40px;">Anno</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="annoalbum" id="annoalbum"  type="text" />
          <label class="cf_label" style="float:left;padding-left:40px;">Etichetta</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="etichettaalbum" id="etichettaalbum"  type="text" />
       </div>
       <div class="cfclear"> </div>
    </div>
    
    <!--end first block (visible) -->
    
    <!-- start hidden block -->
    
    <div id="readrootAlbum" style="display: none;">
    <div class="form_item">
       <div class="form_element cf_textbox">
          <label class="cf_label" style="float:left;">Titolo</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="titoloalbum-more" name="titoloalbum-more[]" type="text" />         
          <label class="cf_label" style="float:left;padding-left:40px;">Anno</label>
           <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="annoalbum-more" name="annoalbum-more[]" type="text" />
          <label class="cf_label" style="float:left;padding-left:40px;">Etichetta</label>
           <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="etichettaalbum-more" name="etichettaalbum-more[]" type="text" />
           <input class="img_x" title="Click per rimuovere l'album" type="button" style="color:#FF0000;font-size:14px;font-weight:bold;margin-left:40px;" value=" X " onclick="deleteFormBlock(this.parentNode.parentNode.parentNode.parentNode);" />
       </div>
       <div class="cfclear"> </div>
    </div>
    </div>
    
    <!--end of hidden block -->
    
    <!-- start placeholder for added blocks -->
    
    <span id="writerootAlbum"></span>
    
    <!-- end placeholder for added blocks -->
    
    <div class="form_item">
       <div class="form_element">
          <input type="button"  title="Click per aggiungere un nuovo album" style="color:#33CC00;font-size:14px;font-weight:bold;" value=" + "  onclick="addFormBlockAlbum()" />
       </div>
    </div>
    
    <!-- fine blocco Album -->
    
    <div class="form_item">
      <div class="form_element cf_text"> <span class="cf_text">Rassegna Stampa</span> </div>
      <div class="cfclear"> </div>
    </div>
    
    <!-- inizio blocco Stampa -->
    
    <!--start first block (visible) -->
    
    <div class="form_item">
      <div class="form_element cf_textbox">
          <label class="cf_label" style="float:left;">Testata</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="testatastampa" id="testatastampa"  type="text" />
          <label class="cf_label" style="float:left;padding-left:40px;">Data</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="datastampa" id="datastampa"  type="text" />
          <label class="cf_label" style="float:left;padding-left:40px;">Autore</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" title="" name="autorestampa" id="autorestampa"  type="text" />
       </div>
       <div class="cfclear"> </div>
    </div>
    
    <!--end first block (visible) -->
    
    <!-- start hidden block -->
    
    <div id="readrootStampa" style="display: none;">
    <div class="form_item">
       <div class="form_element cf_textbox">
          <label class="cf_label" style="float:left;">Testata</label>
          <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="titolostampa-more" name="titolostampa-more[]" type="text" />         
          <label class="cf_label" style="float:left;padding-left:40px;">Data</label>
           <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="datastampa-more" name="datastampa-more[]" type="text" />
          <label class="cf_label" style="float:left;padding-left:40px;">Autore</label>
           <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="autorestampa-more" name="autorestampa-more[]" type="text" />
           <input class="img_x" title="Click per rimuovere l'articolo" type="button" style="color:#FF0000;font-size:14px;font-weight:bold;margin-left:40px;" value=" X " onclick="deleteFormBlock(this.parentNode.parentNode.parentNode.parentNode);" />
       </div>
       <div class="cfclear"> </div>
    </div>
    </div>
    
    <!--end of hidden block -->
    
    <!-- start placeholder for added blocks -->
    
    <span id="writerootStampa"></span>
    
    <!-- end placeholder for added blocks -->
    <div class="form_item">
       <div class="form_element">
          <input type="button"  title="Click per aggiungere un nuovo articolo" style="color:#33CC00;font-size:14px;font-weight:bold;" value=" + "  onclick="addFormBlockStampa()" />
       </div>
    </div>
    
    <!-- fine blocco Stampa -->
    

    And the email template (the interesting part) looks like this:
    <!--inizio risultati per Album -->
    
    <table style="border:0;">
    <?php // first print the static (visible) row ?>
    <tr>
    <td><b>Titolo: </b></td>
    <td style="padding-right:30px;">{titoloalbum}</td>
    <td><b>Anno: </b></td>
    <td>{annoalbum}</td>
    <td><b>Etichetta: </b></td>
    <td>{etichettaalbum}</td>
    </tr>
    <?php
    
    //get the arrays from POST
    $titolo_album_more = JRequest::getVar('titoloalbum-more', null, 'post');
    $anno_album_more = JRequest::getVar('annoalbum-more', null, 'post');
    $etichetta_album_more = JRequest::getVar('etichettaalbum-more', null, 'post');
    
    //loop through the player array and print it and the corresponding item
    foreach ($titolo_album_more as $key=>$value) {
    
       // skip the hidden "source" row
       if ($key != 0) {
          // quick hack: add a divider
          print "\n\n" . '<tr><td colspan="4" style="height:5px;border-bottom: 1px solid gray;margin-bottom: 5px;"> </td></tr>';
          // print the info!
          print "\n" . '<tr><td><b>Titolo   </b></td><td style="padding-right:30px;">' . $value . '</td><td><b>Anno   </b></td><td>' . $anno_album_more[$key] . '</td><td><b>Etichetta   </b></td><td>' . $etichetta_album_more[$key] . '</td></tr>';
       }
    
    }
    
    ?>
    </table>
    
    <!-- fine risultati per Album -->
    
    <div class="form_item">
      <div class="form_element cf_text"> <span class="cf_text">Rassegna Stampa</span> </div>
      <div class="cfclear"> </div>
    </div>
    
    <!-- inizio risultati per Rassegna Stampa -->
    
    <table style="border:0;">
    <?php // first print the static (visible) row ?>
    <tr>
    <td><b>Testata: </b></td>
    <td style="padding-right:30px;">{testatastampa}</td>
    <td><b>Data: </b></td>
    <td>{datastampa}</td>
    <td><b>Autore: </b></td>
    <td>{autorestampa}</td>
    </tr>
    <?php
    
    //get the arrays from POST
    $testata_stampa_more = JRequest::getVar('testatastampa-more', null, 'post');
    $data_stampa_more = JRequest::getVar('datastampa-more', null, 'post');
    $autore_stampa_more = JRequest::getVar('autorestampa-more', null, 'post');
    
    //loop through the player array and print it and the corresponding team
    foreach ($testata_stampa_more as $key=>$value) {
    
       // skip the hidden "source" row
       if ($key != 0) {
          // quick hack: add a divider
          print "\n\n" . '<tr><td colspan="4" style="height:5px;border-bottom: 1px solid gray;margin-bottom: 5px;"> </td></tr>';
          // print the info!
          print "\n" . '<tr><td><b>Testata   </b></td><td style="padding-right:30px;">' . $value . '</td><td><b>Data   </b></td><td>' . $data_stampa_more[$key] . '</td><td><b>Autore   </b></td><td>' . $autore_stampa_more[$key] . '</td></tr>';
       }
    
    }
    
    ?>
    </table>
    
    <!-- fine risultati per Rassegna Stampa -->
    


    Well, I keep on looking at it, checking it, but I cannot find the clue.
    The "Rassegna Stampa" only keeps on displaying the fixed input values, not the user added ones.
    Since I'm not a programmer I'm kind of stuck in here.
    Any help from you pitiful people out there?
    That should be SO appreciated... thanks in advance!
    GreyHead 16 Mar, 2010
    Hi Matreiaweb,

    I'm not sure if this is the problem but input hames with dashes in them often cause problems so try replacing them with underscores. For example, replace:
    <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="titolostampa-more" name="titolostampa-more[]" type="text" />
    with
    <input class="cf_inputbox" style="float:left" maxlength="150" size="20" id="titolostampa_more" name="titolostampa_more[]" type="text" />
    wherever the dashes occur.

    Bob
    TomMC 25 Mar, 2010
    Everything works fine but when the field is set to be required form isn't working any more😟

    I think that the problem is in ID and Name of the fields.. How to make that the Validation rules also work for the dinamically created fields?

    Thanks.
    GreyHead 25 Mar, 2010
    Hi TomMC.

    I'm not sure, I think that the script has to add the validation as well.

    Bob
    TomMC 26 Mar, 2010
    Hi..

    Yes it should add the validation as well but it doesn't..

    checked again before posting.

    Validation rules only apply to the first fields.. non dinamically created and then submit button isn't working any more.. any solution?
    GreyHead 27 Mar, 2010
    Hi TomMC,

    Using for example setProperty('class', 'required') might work but I suspect not (the validations are added when the form is loaded). In that case you'd need to add the code for a custom LiveValidation.

    Bob
    TomMC 27 Mar, 2010

    Hi TomMC,

    Using for example setProperty('class', 'required') might work but I suspect not (the validations are added when the form is loaded). In that case you'd need to add the code for a custom LiveValidation.

    Bob



    Could you possibly give some example?

    I only want the field to be required. Not url, number or any kind of other validations..

    Thanks in advance.
    GreyHead 27 Mar, 2010
    Hi TomMC,

    I'll add it to my list but don't hold your breath, it could take a while.

    Bob
    materiaweb 27 Apr, 2010
    Thanx GreyHead, it worked! I also had a little but lethal mistake of my own, so now it's going like a charm.
    Thank you all again for this wonderful component and the provided support.
    marklandry 07 May, 2010
    Hi,
    This is a great thread!
    Have had a ball getting this to work.
    Only glitch is I've got my form set to republish if wrong captcha which works with the exception of the dynamically added fields.
    Was wondering if there's any way to fix that?
    Thanx for a great discussion!
    Mark
    GreyHead 08 May, 2010
    Hi Mark,

    I'm not sure, ChronoForms does the resetting in PHP using the values from the $_POST array. Because your fields don't exist then it can't see them to add the values.

    I guess you might add some hidden fields with the same names to collect the values and then have your script read these and remove the hidden copies?

    Or you could have the Form HTML add them to a cookie?

    Bob
    pandaboy 21 May, 2010
    First I wanna say than it works just great but like I'm really newbie I have a problem.

    I'm trying to insert dinamycally 2 textareas with the editor tinymce, the problem is that when I click the button it don't copy the textarea instead create a div than visually seems to be the textarea with the editor but obviusly is not a textarea and then doesn't work, could somebody helpme???
    GreyHead 22 May, 2010
    Hi pandaboy,

    What code are you using to create the Rich Text textareas? It sounds as though you may not be loading the editor?

    Bob
    pandaboy 22 May, 2010
    I already solve this, I just dont load the tinymce with Jfactory, I add the textareas normally and load the tinymce with this function:

    
    tinyMCE.init({
    mode : "none",
    theme : "advanced"
    });
    
    function loadtinymce(id) {
       if (!tinyMCE.get(id)) {
          tinyMCE.execCommand('mceAddControl', true, id);
       }
       else {
          tinyMCE.execCommand('mceRemoveControl', true, id);
       }
    }
    


    and then when it finish to load the new block at the end of the function addFormBlock() I just call the function loadtinymce() with the id of the textarea.

    If someone needs I can publish the full code.


    .
    markoadams 23 Jan, 2011
    I have worked my way through this thread and trying to apply it to my own situation and am having a very puzzling problem. If I just copy the instructions that were provided at this post - http://www.chronoengine.com/forums/index.php?option=com_chronoforums&cont=posts&f=5&t=15219&start=15#p45751 - it works fine. So I started to customize with my own hidden block, but every form I have customized using this code has the same problem: nothing happens when you click the submit button! There is an example here: http://dontgetlost.ca/index.php?option=com_chronocontact&chronoformname=AR365_New_Map_Setup.

    It doesn't seem to matter if I have emails on or off, validation on or off etc, nothing happens when the submit button is clicked - no error, no debug info, and if I enable email, no email.

    Anyone have any idea what I could be doing wrong?

    Thanks in advance,

    Mark
    Max_admin 24 Jan, 2011
    Hi Mark,

    Please create a new topic and explain your problem.

    Cheers,
    Max
    Max, ChronoForms developer
    ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
    ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
    missnene 09 Feb, 2011
    Thank you axels! That is just what I needed!
    GreyHead 23 Apr, 2012
    Hi Henniss ,

    Probably not if you are using ChronoForms v4.

    What do you need to do?

    Bob
    Henniss 23 Apr, 2012
    Yes, I'm using v4.

    I'd like my users to be able to add multiple fields to a form in frontend by clicking one button. The data from the form should be emailed and also saved into a database.

    And now that I've written that down, I'm not even sure if I can have dynamic fields with database save, so this is a bit trial and error...
    GreyHead 24 Apr, 2012
    Hi Henniss,

    Create the fields in the Wizard with more copies than you need. You could do this with Wizard elements but it gets very long, I use a Cusotm element and create the copies with PHP putting each into a div with a unique numbered id.

    Use JavaScript in the form to hide all the unwanted divs and disable the inputs in them.

    Add a link to unhide the next div when it is clicked (you need a little counter to track the divs.)

    Give the inputs array names and sort out the data after the form is submitted. You'll probably need to create a custom database save if the repeated records need to go into a second table.

    Bob
    lapo78 25 Apr, 2012
    I used this script and work perfectly:

    The problem now is the validation fields...

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Documento senza titolo</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">	
      (function(jQuery){
              jQuerycountForms_pm = 1;
              jQuery.fn.addForms_pm = function(){
    			  jQuerycountForms_pm++;
                            var myform_pm = "<fieldset><legend>......</legend><ul class='clearfix'>"+
                             "     <li class='ccms_form_element cfdiv_text' id='name_o_gestore_container_div'><label>name</label>"+
                             "     <input type='text' name='name_"+jQuerycountForms_pm+"'></li>"+
                             "     <li class='ccms_form_element cfdiv_text' id='surname_o_gestore_container_div'><label>surname</label>"+
                             "     <input type='text' name='surname_"+jQuerycountForms_pm+"'></li>"+
    						 "  </ul>"+
    						 "  <div class='box-btn_remove'><input type='button' id='remove_pm' value='remove fields' class='btn_remove' /></div>"+
    						 "</fieldset>"; 	
    
                             myform_pm = jQuery(myform_pm);
                             jQuery("#remove_pm", jQuery(myform_pm)).click(function(){
    							jQuery(this).parent().parent().remove(); 
    							});
                             jQuery(this).append(myform_pm);
    						 document.getElementById("count_field").value = jQuerycountForms_pm;
    						 
              };
        })(jQuery);         
    
        jQuery(function(){
            jQuery("#add_pm").bind("click", function(){
                    jQuery("#container").addForms_pm();
            });
        });
    </script>
    </head>
    
    <body>
    
    
    
    
        <div id="container" class="ccms_form_element cfdiv_submit">
        	<fieldset>
        		<legend>...</legend>
                
                <ul>
                    <li class="ccms_form_element cfdiv_text" id="nome_o_gestore_container_div">
                        <label>name</label>
                        <input maxlength="150" title="" label_over="0" hide_label="0" type="text" value="" name="name_1" />
                        <div class="clear"></div>
                        <div id="error-message-name"></div>
                    </li>
                    <li class="ccms_form_element cfdiv_text list30" id="descrizione_intermediario_o_gestore_container_div">
                        <label>surname</label>
                        <input maxlength="150" title="" label_over="0" hide_label="0" type="text" value="" name="surname_1" />
                        <div class="clear"></div>
                        <div id="error-message-surname"></div>
                    </li>
                </ul>	
        	</fieldset> 
    	</div>
    
        <div class="ccms_form_element cfdiv_submit" id="add_altri_opratori_container_div">
        	<input type="hidden" name="count_field" id="count_field" value="1" />
            <input type="button" id="add_pm" value="add fields" />
            <div class="clear"></div>
            <div id="error-message-add_altri_opratori"></div>
        </div> 
    </body>
    </html>
    ttomljen 08 May, 2013
    Hello everyone and thanks for a nice examples.

    My question is whether it is possible to store the data that is written to the added fields in a database using DB save from DB Operations.

    I created a script but do not know how to store the value of a field in a database
    My script would be:
    <script type="text/javascript">   
    var counter = 0;
    function dodavanje_suradnika()
    {
       counter++;
       var newBlockId ='newBlock' + counter;
       var newFields = $('inicijalnisuradnik').clone();
       newFields.setProperty('id', newBlockId);
       newFields.setStyle('display', 'none');
       newFields.getChildren().each(function(newField)
       {
          var theName = newField.getProperty('name');
          var theId = newField.getProperty('id');
    
    	  {
             newField.setProperty('name', counter);
             newField.setProperty('id', counter);
          }
    	  document.getElementById("naziv_instituc"+counter).setAttribute('id', 'naziv_instituc'+(counter+1));
    	  document.getElementById("osoba_s_instit"+counter).setAttribute('id', 'osoba_s_instit'+(counter+1));
    
       });
       var insertHere = document.getElementById('dodanisuradnici');
       
       
    
       
       insertHere.parentNode.insertBefore(newFields,insertHere);   
    
       var addFormBlockSlider = new Fx.Slide( newFields, { duration: 500 } );
       addFormBlockSlider.hide();
       newFields.setStyle('display', 'block');
       addFormBlockSlider.slideIn();
       
    
    	counter2 = ""+counter;
    	document.getElementById(counter2).getElementsByTagName("input")[0].setAttribute('id', 'naziv_instituc'+(counter));
    	document.getElementById(counter2).getElementsByTagName("input")[1].setAttribute('id', 'osoba_s_instit'+(counter));
    }
    function deleteFormBlock(obj)
    {
       var deleteFormBlockSlider = new Fx.Slide( obj, { duration: 500 } );
       deleteFormBlockSlider.slideOut().chain(function()
       {
          obj.remove(obj);
       }); 
    }
    </script>
    <!--start first block  -->
    <div class="form_item">
    <fieldset>
    <legend>(Institution)</legend>
    <ul>
    
      <div class="form_element cf_textbox">
      <li class="ccms_form_element cfdiv_text label_over">
          <label>(Institution name)</label>
          <input class="cf_inputbox" style="float:left" maxlength="255" size="80" title="" name="naziv_instituc1" id="naziv_instituc1"  type="text" />
    	  <div class="clear"></div> 
    	</li> 
    	<li class="ccms_form_element cfdiv_text label_over">
    	  <label >(Name of the person responsible for communication between the Institution and the Centre) </label>
          <input class="cf_inputbox" style="float:left" maxlength="255" size="80" title="" name="osoba_s_instit1" id="osoba_s_instit1"  type="text" />
    	  <div class="clear"></div>
        </li>
    	</div>
     </ul>  
    </fieldset>
     
    </div>
    <!--end first block  -->
    
    <!-- start hidden block -->
    <div id="inicijalnisuradnik" style="display: none;">
    
    
    <div class="form_item">
    <fieldset>
    <legend>(Institution)</legend>
    <ul>
    
       <div class="form_element cf_textbox">
       <li class="ccms_form_element cfdiv_text label_over">
          <label>(Institution name)</label>
          <input id="naziv_instituc" class="cf_inputbox1" style="float:left" maxlength="255" size="80" type="text" />      
          <div class="clear"></div> 
    	</li> 
    	<li class="ccms_form_element cfdiv_text label_over">
    	  <label>(Name of the person responsible for communication between the Institution and the Centre)</label>
          <input id="osoba_s_instit" class="cf_inputbox2" style="float:left" maxlength="255" size="80" type="text" />
    	  <div class="clear"></div>
    	  </li>   
       </div>     
    </ul> 
    
    <input class="img_x" title="(Remove Institution)" type="button" style="color:#696e71;font-size:14px;font-weight:normal;" value=" Ukloni instituciju (Remove Institution)" onclick="deleteFormBlock(this.parentNode.parentNode.parentNode.parentNode);" />
     
    </fieldset>   
    </div>
    </div>
    <!--end of hidden block -->
    
    <!-- start placeholder for added blocks -->
    <span id="dodanisuradnici"></span>
    <!-- end placeholder for added blocks -->
    
    <div class="form_item">
       <div class="form_element">
          <input type="button"  title="(Add Institution)" style="font-size:14px;font-weight:normal;" value="Dodaj instituciju (Add Institution)"  onclick="dodavanje_suradnika()" />
       </div>
    </div>
    GreyHead 08 May, 2013
    Hi ttomljen,

    Yes it is possible, you can save any submitted data. You can probably save it with the DB Save action but that may not be the best way. It will depend on what you need to do with this data later.

    Bob
    ttomljen 08 May, 2013
    I tried conventional way so I created a table and hooked my form to the table, but the data I entered in the added fields are not recorded in the table. In table I predicted multiple fields for multiple entries.
    The table is written only data from fix part of the form, but data from additional fields are not recorded.
    I do not need anything special to do with it except to make export data from a table in excel.
    GreyHead 08 May, 2013
    Hi ttomljen,

    Add a Debugger action to see exactly what is being submitted. If there are array values then a Handle Arrays action will probably help. If not you may need to use PHP in a Custom Code action to make sure that the input names match the column names from your table.

    Bob
    ttomljen 28 May, 2013
    Hello everyone, I made a nice script to add new fields.
    The script gives the ability to remove existing fields and also lists existing records (if you are using Action DB Save).
    I limited to a max of 10 times adding new fields, but you can put in as much as you like, just replace 10 with any number you need.
    I hope it will help someone.


    <script language="Javascript" type="text/javascript">
    <!--
    //Add more fields dynamically.
    
    function addField_institut(area,field,limit) {
    	if(!document.getElementById) return; 
    	var field_area = document.getElementById(area);
    	var all_inputs = field_area.getElementsByTagName("input"); 
    	var last_item = all_inputs.length - 1;
    	var last = all_inputs[last_item].id;
    	var count = Number(last.split("_")[1]) + 1;
    	var countinternal = 1;
     
    	
    	if(count > limit && limit > 0) return;
     
    	if(document.createElement) { //W3C Dom method.
    	var li0 = document.createElement("fieldset");		
    	li0.className = "ccms_form_element cfdiv_text label_over";
    	li0.id = "A"+count;
    	var leg = document.createElement("legend");
    	leg.innerHTML = "Institucija "+count;
    	li0.appendChild(leg);
    	
    	
    		var li1 = document.createElement("div");	
    		var label1 = document.createElement("label");
    		label1.setAttribute("for","1");
    		label1.innerHTML = "Naziv institucije:</br>(Institution name)";
    		li1.appendChild(label1);
    		var input1 = document.createElement("input");
    		input1.id = "institucija_"+count+"_polje_"+countinternal
    		input1.name = "institucija_"+count+"_polje_"+countinternal
    		input1.type = "text";
    		input1.size = "70";
    		li1.appendChild(input1);
    		li0.appendChild(li1);
    		countinternal = countinternal + 1;
    		
    		var li2 = document.createElement("div");	
    		var label2 = document.createElement("label");
    		label2.setAttribute("for","2");
    		label2.innerHTML = "Ime i prezime osobe s institucije odgovorne za komunikaciju s Centrom:</br>(Name of the person responsible for communication between the Institution and the Centre)";
    		li2.appendChild(label2);
    		var input2 = document.createElement("input");
    		input2.id = "institucija_"+count+"_polje_"+countinternal
    		input2.name = "institucija_"+count+"_polje_"+countinternal
    		input2.type = "text";
    		input2.size = "70";
    		li2.appendChild(input2);
    		li0.appendChild(li2);
    		countinternal = countinternal + 1;
    		
    		
    	
    	
    	li0.innerHTML += "<a style=\"cursor:pointer;color:red;\" onclick=\"this.parentNode.parentNode.removeChild(this.parentNode);\">Ukloni instituciju</a>";
    
    	
    	field_area.appendChild(li0);
    		
    	}
    }
    
    function ukloni_institut(param)
    {
    	var id = param;
    	
    	var field_area = document.getElementById("institucija_area");
    	var all_inputs = field_area.getElementsByTagName("input");
    	
    	document.getElementById("institucija_"+id+"_polje_1").value = "";
    	document.getElementById("institucija_"+id+"_polje_2").value = "";
    
    	
    	document.input_submit_200.submit();
    	document.getElementById("institucija_area").removeChild(document.getElementById("A"+count));
    }
    //-->
    </script>
     
    
     
    <ol id="institucija_area">
    <fieldset id="A1" class="ccms_form_element cfdiv_text label_over">
    <legend>Institucija 1</legend>
    <div><label>Naziv institucije:</br>(Institution name)</label><input type="text" name="institucija_1_polje_1" id="institucija_1_polje_1" size="70" /></div>
    <div><label>Ime i prezime osobe s institucije odgovorne za komunikaciju s Centrom:</br>(Name of the person responsible for communication between the Institution and the Centre)</label><input type="text" name="institucija_1_polje_2" id="institucija_1_polje_2" size="70" /></div>
    
    </fieldset>
    
    
    <?php
    	$user = &JFactory::getUser();
    	$form->data['cf_user_id'] = $user->id;
    	$database = JFactory::getDBO();
    	$database->setQuery("SELECT * FROM ////YOUR TABLE//// WHERE cf_user_id = {$user->id}");
    	$data = $database->loadAssoc();
    	
    	for ($i=2; $i<=10; $i++)
    	{	
    	
    		$bla = $form->data("institucija_".$i."_polje_1");
    		$bla2 = $form->data("institucija_".$i."_polje_2");
    	
    	if(strlen($bla) > 1 || strlen($bla2)>1)
    			{
    			echo "<fieldset id=\"A".$i."\" class=\"ccms_form_element cfdiv_text label_over\">
    			<legend>Institucija ".$i."</legend>
    			<div><label>Naziv institucije:</br>(Institution name)</label><input type=\"text\" name=\"institucija_".$i."_polje_1\" id=\"institucija_".$i."_polje_1\" size=\"70\" /></div>
    			<div><label>Ime i prezime osobe s institucije odgovorne za komunikaciju s Centrom:</br>(Name of the person responsible for communication between the Institution and the Centre)</label><input type=\"text\" name=\"institucija_".$i."_polje_2\" id=\"institucija_".$i."_polje_2\" size=\"70\" /></div>
    
    			<a id=\"".$i."\" style=\"cursor:pointer;color:red;\" onclick=\"ukloni_institut(this.id);this.parentNode.parentNode.removeChild(this.parentNode);\">Ukolni instituciju</a>
    			</fieldset>";
        
    			}
    	}
    ?>
    
    
    </ol>
    <input type="button" value="Dodaj novu instituciju" onclick="addField_institut('institucija_area','friend_',10);" />
    NAFOadmin 12 Sep, 2013

    Add a Debugger action to see exactly what is being submitted. If there are array values then a Handle Arrays action will probably help. If not you may need to use PHP in a Custom Code action to make sure that the input names match the column names from your table.



    Bob, can you elaborate on this? I have used the code from the FAQ (http://www.chronoengine.com/faqs/2700-how-can-i-have-a-button-to-add-more-form-inputs.html) in order to dynamically add fields to my form. My problem is that none of the fields, either the first, or the additional ones are saving information to the database because Chronoforms, during the step to create tables, reads their names as: input_name_{$i}.

    How do I get this working, specifically so that the dynamic fields have real names which Chronoforms can use to save to the database?
    NAFOadmin 12 Sep, 2013
    This script is mostly amazing, but I need some help with it. None of the extra fields are saving to the database, or are picked up by the "Create Tables" wizard in Chronoforms. How do I get each of the dynamically created fields to save to the database?

    Hello everyone, I made a nice script to add new fields.
    The script gives the ability to remove existing fields and also lists existing records (if you are using Action DB Save).
    I limited to a max of 10 times adding new fields, but you can put in as much as you like, just replace 10 with any number you need.
    I hope it will help someone.

    Code *SNIP* Code...

    ttomljen 13 Sep, 2013
    You wont see it in Create Table wizard, you have to add them manually.
    So you have to go to phpmyadmin or similar tool and connect to your data base and add fields manually. In my example, I create fields with names: institucija_1_polje_1, institucija_2_polje_1; institucija_2_polje_1,institucija_2_polje_2 ...until institucija_10_polje_1,institucija_10_polje_2.

    I hope this helps...
    GreyHead 13 Sep, 2013
    Hi NAFOadmin,

    Pretty much as ttomljen says - you can also add them in the ChronoForms Create table form.

    You also need to think about whether it might be more useful to add them to a separate linked table with one record for each 'Add one' line. That depends on what the data is to be used for.

    Bob
    jack19 12 Nov, 2013
    Hi,
    Very interesting.
    I wanted to ask if it would be possible to have a field type dropdown multiple selection populated with data from a database?
    Best regards.
    Gioacchino
    jack19 13 Nov, 2013
    Hi Bob,
    it is not clear to me how to integrate it into the code posted by ttomljen.
    🙄
    Best Regards
    Gioacchino
    GreyHead 13 Nov, 2013
    Hi Giaccino,

    Nor me. Choose one and work with it.

    Bob
    jack19 13 Nov, 2013
    Hi Bob,
    the first part of scrpt I resolved in this way:
    <ol id="Expo_area">
    <fieldset id="A1" class="ccms_form_element cfdiv_text label_over">
    <legend>Expo 1</legend>
    <div><label>Exposition:</label><select name="Expo_1_field_1" id="Expo_1_field_1" size="1">
      <?php $bb=$form->data['list'];
    foreach ( $bb as $v ) {
    echo "<option value=\"".$v['cf_id']."\">".$v['ExpoName']."</option>";
    }
    ?>
    </select>
    </div>...


    the second I modified slightly by adding the javascript code with select options (input1.options),

     var li1 = document.createElement("div");   
          var label1 = document.createElement("label");
          label1.setAttribute("for","1");
          label1.innerHTML = "Exposition:";
          li1.appendChild(label1);
          var input1 = document.createElement("select");
          input1.name = "Expo_"+count+"_field_"+countinternal    
          input1.id = "Expo_"+count+"_field_"+countinternal
          input1.type = "select";
          input1.size = "1";
    
          input1.options[0] = new Option('option1','option2'); 
    
          li1.appendChild(input1);
          li0.appendChild(li1);
          countinternal = countinternal + 1;
          
          var li2 = document.createElement("div");   
          var label2 = document.createElement("label");
          label2.setAttribute("for","2");
          label2.innerHTML = "More Info:";
          li2.appendChild(label2);
          var input2 = document.createElement("input");
          input2.id = "Expo_"+count+"_field_"+countinternal
          input2.name = "Expo_"+count+"_field_"+countinternal
          input2.type = "text";
          input2.size = "70";
          li2.appendChild(input2);
          li0.appendChild(li2);
          countinternal = countinternal + 1;

    I tried in different ways but I can not make it work.
    Any other ideas?
    Best regards.
    Gioacchino
    jack19 10 Dec, 2013
    Hi,
    this is my solution, it works perfectly when records are inserted as new.
    The problem comes when I have to edit the data from the DB: select option is not populated and I can not find the solution.
    <?php
    // Carico le righe del DB
    
    $results = array();
    $i = 1;
    $results[] = "input1.options[0] = new Option('Seleziona una voce','');";
    foreach ( $form->data['list'] as $a ) {
     $results[] = "input1.options[".$i."]  = new Option('".addslashes($a['NomeExpo'])." - ".addslashes($a['LuogoExpo'])."','".$a['cf_id']."');";
        $i++;
    }
    
    $results = implode("\n", $results);
    
    // Fine righe DB
    ?>
    
    <script language="Javascript" type="text/javascript">
    <!--
    //Add more fields dynamically.
    
    function addField_institut(area,field,limit) {
       if(!document.getElementById) return; 
       var field_area = document.getElementById(area);
       var all_inputs = field_area.getElementsByTagName("input"); 
       var last_item = all_inputs.length - 1;
       var last = all_inputs[last_item].id;
       var count = Number(last.split("_")[1]) + 1;
       var countinternal = 1;
    
       
       if(count > limit && limit > 0) return;
    
       if(document.createElement) { //W3C Dom method.
       var li0 = document.createElement("fieldset");      
       li0.className = "ccms_form_element cfdiv_text label_over";
       li0.id = "A"+count;
       var leg = document.createElement("legend");
       leg.innerHTML = "Expo "+count;
       li0.appendChild(leg);
       
       
          var li1 = document.createElement("div");   
          var label1 = document.createElement("label");
          label1.setAttribute("for","1");
          label1.innerHTML = "Nome Expo:"; 
          li1.appendChild(label1);
          var input1 = document.createElement("select");
          input1.name = "Expo_"+count+"_campo_"+countinternal   
          input1.id = "Expo_"+count+"_campo_"+countinternal
          input1.type = "select";
          input1.size = "1";
     
          <?php echo $results; ?>
      
          li1.appendChild(input1);
          li0.appendChild(li1);
          countinternal = countinternal + 1;
          
          var li2 = document.createElement("div");   
          var label2 = document.createElement("label");
          label2.setAttribute("for","2");
          label2.innerHTML = "Informazione aggiuntiva:</br>(Inserire l'informazione)";
          li2.appendChild(label2);
          var input2 = document.createElement("input");
          input2.id = "Expo_"+count+"_campo_"+countinternal
          input2.name = "Expo_"+count+"_campo_"+countinternal
          input2.type = "text";
          input2.size = "70";
          li2.appendChild(input2);
          li0.appendChild(li2);
          countinternal = countinternal + 1;
          
          
       
       
       li0.innerHTML += "<a style=\"cursor:pointer;color:red;\" onclick=\"this.parentNode.parentNode.removeChild(this.parentNode);\">Elimina campo</a>";
    
       
       field_area.appendChild(li0);
          
       }
    }
    
    function svuota_campo(param)
    {
       var id = param;
       
       var field_area = document.getElementById("Expo_area");
       var all_inputs = field_area.getElementsByTagName("input");
       
       document.getElementById("Expo_"+id+"_campo_1").value = "";
       document.getElementById("Expo_"+id+"_campo_2").value = "";
    
       
       document.input_submit_200.submit();
       document.getElementById("Expo_area").removeChild(document.getElementById("A"+count));
    }
    //-->
    </script>
    
    
    
    <ol id="Expo_area">
    <fieldset id="A1" class="ccms_form_element cfdiv_text label_over">
    <legend>Expo 1</legend>
    <div><label>Nome Expo:</label><select name="Expo_1_campo_1" id="Expo_1_campo_1" size="1">
      <?php $bb=$form->data['list'];
    echo "<option value=\"\">Selezionare una voce</option>";
    foreach ( $bb as $v ) {
    echo "<option value=\"".$v['cf_id']."\">".$v['NomeExpo']." - ".$v['LuogoExpo']."</option>";
    }
    
    ?>
    </select>
    </div>
    <div><label>Informazione aggiuntiva:</br>(Inserire l'informazione)</label><input type="text" name="Expo_1_campo_2" id="Expo_1_campo_2" size="70" /></div>
    
    </fieldset>
    
    
    <?php
       $user = &JFactory::getUser();
       $form->data['cf_user_id'] = $user->id;
       $database = JFactory::getDBO();
       $database->setQuery("SELECT * FROM ////YOUR TABLE//// WHERE cf_user_id = {$user->id}");
       $data = $database->loadAssoc();
       
       for ($i=2; $i<=10; $i++)
       {   
       
          $bla = $form->data("Expo_".$i."_campo_1");
          $bla2 = $form->data("Expo_".$i."_campo_2");
       
       if(strlen($bla) > 1 || strlen($bla2)>1)
             {
             echo "<fieldset id=\"A".$i."\" class=\"ccms_form_element cfdiv_text label_over\">
             <legend>Expo ".$i."</legend>
             <div><label>Nome Expo:</label>
    <select name=\"Expo_".$i."_campo_1\" id=\"Expo_".$i."_campo_1\" size=\"1\"> 
    
     
    
    </select>
    </div>
             <div><label>Informazione aggiuntiva:</br>(Inserire l'informazione)</label><input type=\"text\" name=\"Expo_".$i."_campo_2\" id=\"Expo_".$i."_campo_2\" size=\"70\" /></div>
    
             <a id=\"".$i."\" style=\"cursor:pointer;color:red;\" onclick=\"svuota_campo(this.id);this.parentNode.parentNode.removeChild(this.parentNode);\">Svuota il campo</a>
             </fieldset>";
        
             }
       }
    ?>
    
    
    </ol>
    <input type="button" value="Aggiungi nuovo" onclick="addField_institut('Expo_area','friend_',10);" />

    Best Regards.
    GreyHead 11 Dec, 2013
    Hi Gioacchino,

    I'm sorry I don't know what this code is trying to do or why you are using it. I thought that you were trying to use a Double Drop-down with Ajax from the FAQ but that doesn't require you to build the whole element.

    When you use a form like this for editing you have to repeat any Ajax lookups when the form loads so that the input values are set correctly.

    Bob
    This topic is locked and no more replies can be posted.