Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

How to dynamically add form elements via JavaScript

February 21st, 2008  |  Published in javascript  |  65 Comments



Not all forms are meant to be static. Sometimes, you want to allow the users to add certain parts of the form as they need them. Here is a nice example of dynamically adding inputs to your form as users need them. In addition, an input limit has been implemented in the script and it is set to 3.

Demo
Entry 1


Here is the plain HTML for the form:

<script src="/wp-includes/js/addInput.js" language="Javascript" type="text/javascript"></script>
<form method="POST">
     <div id="dynamicInput">
          Entry 1<br><input type="text" name="myInputs[]">
     </div>
     <input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>

When the user clicks on the Add another text input button, the addInput JavaScript function is executed and given the dynamicInput argument which is the name of the div that contains all our text inputs. Here is what our JavaScript function looks like:

var counter = 1;
var limit = 3;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

There are a couple of global variables:

  • counter – Tracks the number inputs being added.
  • limit – The maximum number inputs allowed for the user to add. In this case, we are limiting the user to a maximum of 3 input texts that they can submit with the form.

The addInput JavaScript function expects a parameter, which in this case is the id of the div, to add the dynamic text inputs. Once executed, the function will first check to see if the maximum number of input texts have already been used. If so, an alert will be given stating that the limit has been reached.

If the limit has not been reached, then the else block of the code is executed. A new div element is created and the inner HTML is set with 2 things:

  • Entry # – The global variable, counter, keeps track of the current number of text inputs that are in the form.
  • The input text element – The name of these text inputs,myInputs[], is followed by square brackets to indicate that it is an array. This will be more important later on when the form is submitted using the POST method.

If the form gets submitted to a PHP file, you can easily access each input value for your myInputs array. Here is the PHP code for doing just that:

$myInputs = $_POST["myInputs"];
foreach ($myInputs as $eachInput) {
     echo $eachInput . "<br>";
}

This is just a sample code to echo all the text input values that were sent from the form. An array variable, $myInputsPHP, is initialized with the myInputs from the form. Then, the foreach loop will go through each value and print them out.

Here is another version of this script that adds different types of inputs such as text fields, radio buttons, checkboxes, and textareas. To simplify things, the limit functionality has been removed.

Demo
Let’s start adding some inputs of different types.

Here is the plain JavaScript code for the addAllInputs function. It accepts 2 arguments:

  • div id – This is the div id where all the dynamic inputs will be added to.
  • input type – This is the type of input that we want to add.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var counterText = 0;
var counterRadioButton = 0;
var counterCheckBox = 0;
var counterTextArea = 0;
function addAllInputs(divName, inputType){
     var newdiv = document.createElement('div');
     switch(inputType) {
          case 'text':
               newdiv.innerHTML = "Entry " + (counterText + 1) + " <br><input type='text' name='myInputs[]'>";
               counterText++;
               break;
          case 'radio':
               newdiv.innerHTML = "Entry " + (counterRadioButton + 1) + " <br><input type='radio' name='myRadioButtons[]'>";
               counterRadioButton++;
               break;
          case 'checkbox':
               newdiv.innerHTML = "Entry " + (counterCheckBox + 1) + " <br><input type='checkbox' name='myCheckBoxes[]'>";
               counterCheckBox++;
               break;
          case 'textarea':
	       newdiv.innerHTML = "Entry " + (counterTextArea + 1) + " <br><textarea name='myTextAreas[]'>type here...</textarea>";
               counterTextArea++;
               break;
          }
     document.getElementById(divName).appendChild(newdiv);
}
Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Responses

Feed Trackback Address
  1. Eric Ma says:

    March 24th, 2008 at 11:57 pm (#)

    Thanks for this code! It’s been immensely useful… but as I am a beginner to Javascript, I was wondering, how do we remove an element that we’ve added? I’ve tried (very naively, I think) to add the code:

    function removeInput(divName){
    document.getElementById(divName).removeChild(newdiv);
    }

    but I think that doesn’t do anything… am I missing something?

    Thanks a lot!! =)

    [Reply]

  2. admin says:

    March 25th, 2008 at 7:47 pm (#)

    Hi Eric. The function should work. Are you sure that divName is a parent element of newdiv? If not, just create some div tags around newdiv and just use that as your parent element for divName.

    Since you have this sort question, there might be others with the same question. I have created a new post How to dynamically remove/delete elements via JavaScript that covers this topic =)

    [Reply]

    Anonymous reply on December 29th, 2008 10:35 pm:

    Hi admin,
    I’m prgramming in JAVA struts2, I used the above code for dynamically displaying textarea on button click. But I’m unable to get the content of the textarea which is dynamically generated by javascript into to my programme.

    In programme, only first textarea value is retreived correctly, but next textareas values are null.
    So, what is the correct way to retreive the value for javascript generated textareas into programme.

    [Reply]

    George reply on February 19th, 2009 11:21 pm:

    Hi admin,
    thank a lot for the both scripts (add and remove), it works exellent individually, but if I wont to remove dynamicly last editted row (by add script) it fails.
    How to combine your two scripts? My imagine is to have edit row with two button (add and remove). Could you help me. Thanks. GB.

    [Reply]

  3. matthew tennant says:

    April 7th, 2008 at 8:51 am (#)

    Thanks so much for posting this, i have been trying to get an understanding of this for the last few days, this has really helped me to make sense of my problem.

    Just one query. I am hoping to pass the output of this form to a database. I then want to retrieve the number of fields and their accompanying values to a form for a user to update and potentially add more fields.

    is it possible to pass a variable from php to this script. When i looked at this before i seem to remember drawing a bit of a blank.

    Cheers again

    Matthew

    [Reply]

  4. admin says:

    April 7th, 2008 at 10:05 pm (#)

    Hi Matthew,

    You can certainly pass variables from PHP to JavaScript. For example, you can pass a variable in the url string such as:

    http://mysite.com/form.php?myVariable=myValue

    Then, in your PHP script, form.php, you can have something like this:

    <?php
    $variable = $_GET['myVariable'];
    ?>
    <header>
    ...
    </header>
    <body onload="myJavaScriptFunction('<?=$variable;?>')">
    ...
    </body>

    For this example, I set $variable equal to the value for myVariable which is derived from the GET string. Then, I use the JavaScript onload event, as an example, to launch my JavaScript function and pass along the variable from my PHP variable.

    I hope this example helps.

    [Reply]

    Charles reply on August 9th, 2008 7:00 pm:

    Shouldn’t it be the following?

    <body onload=”myJavaScriptFunction(’’)”>

    or does =$variable automatically print out the variable?

    Looks odd to me. I haven’t seen this convention.

    [Reply]

    Charles reply on August 9th, 2008 7:01 pm:

    Hm…didn’t display correctly.

    I wanted to change ‘=$variable’ to ‘ echo $variable’.

    [Reply]

  5. Alper says:

    May 5th, 2008 at 2:20 pm (#)

    really so much thnx. i was trying to find this for so many years :)

    [Reply]

  6. Knight says:

    May 30th, 2008 at 1:59 am (#)

    Hi, I need a little help here, i have a form that add new input texts, like this:
     
     
    without a limit of inputs, after the form be submited how i make all this inputs like this?
    $ed1 = $_POST['ed1'];
    $ed2 = $_POST['ed2'];
    $link1 = $_POST['link1'];
    $link2 = $_POST['link2'];

    $template->assign_vars(array(
    ‘ED1′ => $ed1,
    ‘ED2′ => $ed2,
    ‘LINK1′ => $link1,
    ‘LINK2′ => $link2,

    where in the final page they will show like this:
    Some text ‘ED1′
    Some text ‘ED2′

    [Reply]

  7. Knix says:

    May 31st, 2008 at 11:14 pm (#)

    Hi Knight,

    For the HTML of your form, make sure you indicate the names of all your inputs with brackets so that it is passed as an array to the PHP file. For example:


    <input type="text" name="ed[]" value="link1">
    <input type="text" name="ed[]" value="link2">

    In your PHP code, you can have this to generate the links:


    $ed = $_POST['ed'];
    $counter = 1;
    foreach ($ed as $link) {
    echo "<a href='" . $link . "' rel="nofollow">ed" . $counter . "</a>";
    $counter++;
    }

    I’m not sure if I follow your example correctly but I hope this helps.

    [Reply]

  8. Matthew Atkins says:

    June 29th, 2008 at 6:03 am (#)

    Hi,

    Thank you for this tutorial. It is definitely the most comprehensible one on this subject I have found.

    But I am having a problem. I can’t seem to retrieve the text typed into the dynamically generated fields using the php $_POST['textarea_name']. I can’t see what i’m doing wrong, but it’s almost as if the textareas that are generated with javascript just aren’t part of the form that’s being submitted, even though they get generated between the the two tags. Anyone else had this problem?

    Cheers.

    [Reply]

    Knix reply on June 30th, 2008 9:08 am:

    Hi Matthew,

    Can you please post your code so that I may take a look at it?

    What I am interested in seeing is the HTML code that is dynamically generated for the textarea. Please include the form tags as well.

    Thanks.

    [Reply]

    Knix reply on July 1st, 2008 7:05 am:

    Hi Matthew,

    If you used the following notation to create the dynamic input, then I may know what you are doing wrong:

    1
    
    <input type="text" name="myInputs[]">

    The brackets for the name attribute myInputs will be passed as an array to your PHP file when you submit the form. To access each variable, I would just use a foreach loop.

    1
    2
    3
    4
    
    $myInputs = $_POST["myInputs"];
    foreach ($myInputs as $eachInput) {
         echo $eachInput . "<br>";
    }

    If you know that only one input will be passed, then you can simply use $_POST['myInputs'][0].

    I hope this helps.

    [Reply]

    Matthew Atkins reply on July 1st, 2008 7:16 am:

    Thank you for your help Knix.

    I managed to solve the problem, it was a silly thing, but it cost me days. Basically what I had done was put the start form tag inside the start table tag, but before the tr and td. So kind on in “no man’s land”. This is not usually a problem, all the form inputs usually work fine and so I did not anticipate any problem. But for some reason the dynamically created inputs just don’t post any information if the form tag is in this place. The solution was simple, i just had to move the form tag above the table tag. Quite a strange problem. Be wary of that one.

    [Reply]

    vhedonist reply on September 6th, 2008 4:34 am:

    Thanks Matthew. Had the same problem. Had you not mentioned where you went wrong, I too probably would have taken days to figure out;)

  9. shamim says:

    July 3rd, 2008 at 5:01 pm (#)

    I would like to know how I can update MySql database with these dynamic fields?

    [Reply]

    Knix reply on July 3rd, 2008 11:19 pm:

    Hi shamim,

    This is a very general question and there are many ways to do this depending on what type of server-side language you are using. If you are submitting and posting your form to a PHP page, you can access the variable via the $_POST global variable.

    Sample HTML form:

    1
    2
    3
    4
    5
    
    <form method='POST' action='submitToDB.php'>
        First Name: <input type='text' name='firstName'>
        Last Name: <input type='text' name='lastName'> 
        <input type='submit' value='Submit'>
    </form>

    The following would be your submitToDB.php page:

    1
    2
    3
    4
    
    <?php
       $firstName = $_POST['firstName'];
       $lastName = $_POST['lastName'];
    ?>

    For the actual MySQL database connection, I will refer to this great tutorial.

    I hope this information helps.

    [Reply]

  10. Michael Millett says:

    August 5th, 2008 at 2:11 pm (#)

    Great tutorial. And great comments. Thanks especially to Matthew Atkins and your discovery of the misplaced form tag negating the submission of dynamically created inputs. Very helpful.

    [Reply]

  11. Remo Harsono says:

    August 8th, 2008 at 1:38 am (#)

    Great tutorial, great comments, and…great response :)

    [Reply]

  12. Charles says:

    August 9th, 2008 at 7:03 pm (#)

    Awesome tutorial to get me started. I’m reading your other article about removing elements. My only question is I’m creating new div’s. To remove, I need to get by ID. However, how do you assign an id to a programmatically created div?

    var newdiv = document.createElement(‘div’);
    .
    .
    .

    how do i remove this later down the line? you should examples of how to remove div’s that were previously hardcoded in the HTML…but programmatically created??

    [Reply]

    Knix reply on August 10th, 2008 10:08 am:

    Hi Charlie,

    At the time you programmatically create your div, you know the id. This would also be the best time to create the button or whatever method you choose to programmatically remove the div as well.

    [Reply]

    vhedonist reply on September 6th, 2008 4:45 am:

    Hi charlie,
    var newdiv = document.createElement(’div’);
    newdiv.setAttribute(‘id’,id_value_here);

    to remove;
    1.grab the reference of parent element(one way using document.getElementByID)
    2.grab the reference of the child element(using document.getElementByID, id is that which was set using setAttribute() )

    [Reply]

    Charles reply on September 7th, 2008 8:32 am:

    thank you!!! exactly what i didn’t know but needed! i had gone many round about ways to make it work but this is exactly what cleans it all up.

    thanks again…learning new JS/DOM calls everyday!

    [Reply]

    vhedonist reply on September 6th, 2008 4:50 am:

    Oh forgot something,
    to remove;
    1.grab the reference of parent element(one way using document.getElementByID)
    2.grab the reference of the child element(using document.getElementByID, id is that which was set using setAttribute() )
    3.parent_element’s_reference.removeChild(child_element’s_reference);

    [Reply]

  13. rico says:

    October 20th, 2008 at 7:38 am (#)

    Hello! I just want you to know how thankful I am for your script. It could have taken me weeks for this script.

    Cheers to you man!

    [Reply]

  14. Travis says:

    November 11th, 2008 at 9:37 am (#)

    Hi I have a form that is like this:

    QTY

    How can I change the addInput.js from the first example to create another text area and a QTY text field like my example

    -thanks

    [Reply]

    Travis reply on November 11th, 2008 9:39 am:

    sorry here is the url to my examle

    http://www.kwalu.com/example.html

    [Reply]

    Knix reply on November 11th, 2008 9:26 pm:

    Using the original function as an example, you just have to add another textarea:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    var counter = 1;
    var limit = 3;
    function addInput(divName){
         if (counter == limit)  {
              alert("You have reached the limit of adding " + counter + " inputs");
         }
         else {
              var newdiv = document.createElement('div');
              newdiv.innerHTML = "Entry " + (counter + 1) + " <br /><textarea name='textAreas[]' cols=40 rows=6></textarea><br />QTY<input type='text' name='myInputs[]'>";
              document.getElementById(divName).appendChild(newdiv);
              counter++;
         }
    }

    [Reply]

  15. msprog says:

    January 7th, 2009 at 1:25 pm (#)

    Hi to everyone.
    It is very nice tutorial.Thank you for sharing.
    I would like to ask something related with this subject.
    How can I add a field inside a table row?
    I think I have to also add a row to the table.Am I right?

    [Reply]

    Knix reply on February 28th, 2009 9:11 am:

    Yes, you will have to add a new row to the table, unless you have the table already prefilled with empty rows (but then it will have a limit). I would just keep tacking on rows.

    [Reply]

  16. Eric says:

    January 10th, 2009 at 12:18 pm (#)

    Hi, this is a great tutorial and I’ve got it working perfectly. One question: on long forms it frequently is necessary to have the user submit to a summary page with the option to go back and change their input. However, when you go back to the page with the dynamically created fields, they are gone along with whatever values were filled out by the user. I am specifically using this for textarea fields and I am using PHP. Is there a way to have the form either retain the fields and values or recreate them somehow? Thank you!

    [Reply]

    Knix reply on February 28th, 2009 9:25 am:

    In this case, I would have the same PHP page handle both the submission and the form itself. On your submission page, you can have a “hidden” form that saves all the user’s input and have the submit button labeled as “Back to Form” and that should work. This way you can use same variables for both the form (if the user goes back) or to handle the page submission. Here is an example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    <?php
    if ($_POST['submit']) { // if user pressed the submit button
    // process form
    ?>
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
    <input type="hidden" name="email" value="<?=$_POST['email'];?>">
    <input type="submit" name="back" value="Back to Form">
    </form>
    <?     
    }
    else {
    // display the form
    ?>
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
    <input type="text" name="email" value="<?=$_POST['email'];?>">
    <input type="submit" name="submit" value="Submit">
    </form>
    <?
    }
    ?>

    I have not tested this but I think you get the idea.

    [Reply]

    Eric reply on March 4th, 2009 9:27 am:

    Thank you for your suggestion Knix but as soon as you navigate from the page whether by going to a different page or submitting the form to the same page, the dynamically generated form fields disappear. I know how to use PHP to fill in the posted values however the fields that were added to the form are gone. I’m looking for a way to recreate these fields after the form is submitted.

    [Reply]

    Knix reply on March 4th, 2009 10:06 am:

    Hi Eric,

    I understand the issue now but this suggestion should be able to handle that as well. Let’s say you have 3 input text fields that are dynamically generated with the following names: text1, text2, text3. When the user submits the page, the PHP script will know that 3 text fields were created. When the user uses the “Back” button on the form, you can recreate this form in PHP. Of course, if the user uses the back button in the browser, everything might be deleted. The only way to handle that case would be to use cookies.

    I hope this helps.

    Knix

    Eric reply on March 4th, 2009 10:49 am:

    Actually no, the fields are created via javascript – a client side scripting language, in response to the users input. PHP is run on the server side. When you return to the page the fields are gone as there is no way for the javascript to know to recreate the fields. There may be a way to do this with Ajax but it is beyond my knowledge so I am asking here if someone does know of a way to recreate the fields. If someone can break a form by clicking the back button then it is something that needs to be addressed.

    Knix reply on March 4th, 2009 11:58 am:

    Hi Eric,

    You are absolutely right about PHP being a server side scripting language and that is why this is possible. When the user submits the form, PHP takes over and handles the form information. At this point, your PHP script should know exactly how many fields were generated. Now, knowing this information, your PHP script should be able to generate the “hidden” form that takes the user “Back” to the form. When the user actually presses the “Back” button, they will in fact be submitting the hidden form to the same PHP page. The PHP page will still know how many fields were generated and should be able to dynamically recreate the fields for you. There is no JavaScript needed for this.

    Knix

    Eric reply on March 4th, 2009 12:14 pm:

    I gotcha on re-creating the form fields via PHP – makes sense and I can do that but if the user hits the back button – which is very possible – I don’t see how to handle it unless there is a javascript solution, even if I create session variables. If you know how to do this can you provide some example code?

    [Reply]

    Knix reply on March 4th, 2009 3:28 pm:

    Here is the basic outline of what the code would look like:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
    if ($_POST['submit']) { // if user pressed the submit button
    // process form
    // calculate number of inputs that were generated and store to variable $numInputs
    ?>
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
    <input type="hidden" name="numInputs" value="<?=$numInputs;?>"> 
    <!-- store all the values of these inputs to hidden fields as well -->
    <input type="submit" name="back" value="Back to Form">
    </form>
    <?     
    }
    else if ($_POST['back']) { // user used back button
       // for loop to generate inputs
       for ($counter = 0; $counter < $_POST['numInputs']; $counter += 1) {
          // generate html for inputs using values saved in hidden fields
       }
    }
    else {
    // display the form
    ?>
    <form action="<?=$_SERVER['PHP_SELF'];?>" method="POST">
    <input type="text" name="email" value="<?=$_POST['email'];?>">
    <input type="submit" name="submit" value="Submit">
    </form>
    <?
    }

    Eric reply on March 4th, 2009 3:36 pm:

    Thank you! Very helpful

  17. Sheikha says:

    February 24th, 2009 at 2:41 am (#)

    Great post, thank you.

    [Reply]

  18. Dukester says:

    February 26th, 2009 at 8:49 am (#)

    This has been a great reference, thank you! That being said, I’m wondering if you can help me! I am trying to take computed results from some javascript dynamic created fields in a form and pass them to a PHP script for emailing the results. However, none of the fields inside the javascript areas get passed. Any ideas? here is the code:
    I’ll remove most of the dropdown options for brevity.

    something simple

    2) tbl.deleteRow(tbl.rows.length – 1);
    }

    function copyField(o0,o1) {
    document.getElementById(o1).value = document.getElementById(o0).value;
    }

    function getTotals(tblStr, o3, o4, o5, o6, o7, o8)
    // o4 – exemption, o5 – subtotal, 06=mitigation rate, 07=new subtotal
    {
    var tbl = document.getElementById(tblStr);
    var c = 0;
    var myTotal = 0;
    var outTxt0 = 0;
    var outTxt1 = 0;
    var outTxt2 = 0;
    var exemptionrate = 10;
    var outTxt3 = document.getElementById(o3);
    var outTxt4 = document.getElementById(o4);
    var outTxt5 = document.getElementById(o5);
    var outTxt6 = document.getElementById(o6);
    var outTxt7 = document.getElementById(o7);
    var outTxt8 = document.getElementById(o8);
    var lastRow = tbl.rows.length – 1;
    for (c=1; c<=lastRow; c++) {
    outTxt0 = tbl.rows[c].cells[0].innerHTML;
    outTxt1 = tbl.rows[c].cells[1].firstChild.value;
    outTxt2 = tbl.rows[c].cells[2].firstChild[tbl.rows[c].cells[2].firstChild.selectedIndex].text;
    outTxt3.value = parseInt(outTxt1) * parseInt(outTxt2);
    myTotal = parseInt(myTotal) + parseInt(outTxt3.value);
    }
    outTxt3.value = myTotal;
    outTxt4.value = parseInt(myTotal) / parseInt(exemptionrate);
    outTxt5.value = parseInt(myTotal) – parseFloat(outTxt4.value);
    outTxt6.value = 5;
    outTxt7.value = parseFloat(outTxt5.value) / parseFloat(outTxt6.value);
    outTxt8.value = outTxt7.value;
    }

    function getTotals2(o0, tblStr1, p3, p4, p5, p6, p8)
    //
    {
    var outTxt7 = document.getElementById(o0);
    var mitRate = 5;
    var tbl1 = document.getElementById(tblStr1);
    var outTxt3 = document.getElementById(p3);
    var outTxt4 = document.getElementById(p4);
    var outTxt5 = document.getElementById(p5);
    var outTxt6 = document.getElementById(p6);
    var outTxt8 = document.getElementById(p8);
    var lastRow = tbl1.rows.length – 1;
    var c = 0;
    var myTotal = 0;
    for (c=1; c

    Part 1 – Mitigation

    Row
    Qty
    DBH
    <!– Total –>

    1

    15
    16

    <!– <input type=”text” id=”txtRowTotal” size=”6″ value=”0″
    –>

    Combined total to be mitigated in inches:

    - 10% Exemption:

    Subtotal:

    Divided by rate of mitigation:

    Mitigation subtotal:

    Part 2 – Credit

    Row
    Qty
    DBH

    1

    Combined total to be credited in inches:

    Divided by rate of mitigation:

    Number of 2″ trees to be credited:

    Part 3 – Planting Requirements
    Mitigation subtotal:

    – Credit for inches DBH preserved: 


    Number of 2″ trees to be planted

    Name

    Last name

    Email

    Comments

    Send form!

    [Reply]

  19. Lloyd says:

    May 20th, 2009 at 2:58 am (#)

    Great tutorial, been looking well over 2 hours for something this straight forward and well explained. Thanx

    [Reply]

  20. minie says:

    June 10th, 2009 at 11:38 pm (#)

    wonderful tutorial…jus wat ive been lookin for.TQ!

    need ur help anyway…. how to save this inputs of the dynamic rows into the database? ive been tryin but the input in the second row overlaps the input in first row. im having trouble with this… can anyone plz help me out?

    thank you!

    [Reply]

  21. Steve Caldwell says:

    July 2nd, 2009 at 9:20 am (#)

    Let me try this again since my last post cut off some code.

    I would like to post how I got this data to post with ColdFusion, since I only saw PHP. I’m sure there is a better way to do this with JSON/CFarray and welcome some advice on that.

    BTW, Mine dynamically creates a select list and populates it with a query:

    var newdiv = document.createElement(’div’);
    newdiv.setAttribute(’id’,’author’ + (counter + 1));
    newdiv.innerHTML = “” + “Author ” + (counter + 1) + “: ” + “ N/A#myQuery.lastname#, #myQuery.firstname# ” + ” remove author” ;
    document.getElementById(divName).appendChild(newdiv);
    counter++;
    }
    }

    The select name “authors” creates a comma separated list of the values of the dynamically populated lists.

    Then on my .cfc action page I had to do a little finagling to get it to insert in my cfquery properly:

    INSERT INTO PUBLICATIONS (author#i#,
    VALUES (‘#author#’,0,

    So if I added 3 lists dynamically on the entry form, it inserts the 3 values from those lists into author2, author3, and author4, and inserts 7 ‘0′ values to the other 7 author fields in my db.

    Hope this helps all you CF junkies.

    [Reply]

  22. Michal Marianek says:

    July 6th, 2009 at 3:04 am (#)

    Hello
    Thank you for this code. This is exactly what I was looking for!! I just wanted to ask . Is there possible to add a remove function? There would be a remove button under each fotm instance so user could add a new ones and/or remove existing ones. It would be great!
    Thank you
    Michal

    [Reply]

  23. Andre says:

    July 16th, 2009 at 3:38 am (#)

    Thank you so much for the code and the explanations. This is really great! I would really appreciate if anyone could help me with the following: I would like to use this skript but i want the »Add another Input« button to create several input fields at the same time. For better explanation:
    When starting i would like to have 3 input fields in a row:
    Name | Age | Country
    and when the »Add another Input« button is pressed another three field Name | Age | Country row should appear.

    Thank you once again,

    tm

    [Reply]

    Knix reply on July 17th, 2009 12:31 am:

    Hi Andre,

    The function can be modified by adding a for loop which creates 3 input fields instead of 1:

    1
    2
    3
    4
    5
    6
    7
    
    function add3Inputs(divName){
        for (i=1; i<=3; i++) {
            var newdiv = document.createElement('div');
            newdiv.innerHTML = "Entry " + i + " <br><input type='text' name='myInputs[]'>";
            document.getElementById(divName).appendChild(newdiv);
        }
    }

    Please note that this code is not tested but I hope you get the idea.

    [Reply]

    Rob reply on August 17th, 2009 11:51 am:

    You could do that a lot neatter using JQuery and ther append() fucntion. Or even better better, simple use clone() on the parrent element :)

    [Reply]

  24. Anonymous says:

    July 25th, 2009 at 8:29 am (#)

    Hi,

    How to validate the value of dynamically added form element(i.e textbox1 textbox2 etc.) using javascript.

    Thx,
    SAN

    [Reply]

  25. Rob says:

    July 25th, 2009 at 7:42 pm (#)

    Nice article! I made an extended and more compact version of your idea using JQuery, the article also explains how to save dynamically added form values to a many-many database structure, using mysql/php. See:

    http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/

    [Reply]

  26. Pumpkin says:

    July 26th, 2009 at 10:02 pm (#)

    HI, I am new to add form elements dynamically.

    From now on, I add rows successfully.
    However, when i submit the form, i cant get the data which are in the newly add rows.

    I try to submit the form by “post” and “get” both method are failed to get the value in the newly added rows..

    ..
    if (isset($_POST['submit'])) {
    $inputs = $_POST["inputs"];
    echo $inputs [0]; // <— original row is ok to output data here!
    echo $inputs [1];
    echo $inputs [2];
    echo $inputs [3];
    echo $inputs [4];
    echo $inputs [5]; // <— newly added row by pressing the button is FAILED to output data here!
    echo $inputs [6];
    }

    [Reply]

    Knix reply on July 30th, 2009 7:29 am:

    Hi Pumpkin,

    Can you please post the html of your form? That will definitely give me some clues.

    Knix

    [Reply]

  27. nasim says:

    August 15th, 2009 at 7:54 am (#)

    hello
    after thanking you for the great tutorial i wanted to ask you a question about a case which i faced when i tried to add multiple items to form each time,the problem is that all added items go right after the first existing element in the div section of html form while i need them to be added after the last element of my div section of html…any help?

    [Reply]

    Rob reply on August 17th, 2009 11:50 am:

    Hi,

    Again, this is simply looping through a series of associative arrays. E.g. you’d need to name each field as an array – field1[] , field2[] etc etc and then loop through you’re post data sequentially E.g – say you were adding 2 fields each time – name and email.

    if (isset($_POST['cname'])) {

    for ( $i=0; $i<count($_POST['cname']); $i++) {
    $contactname = $_POST['cname'][$i];
    $conatctemail = $_POST['cemail'][$i];

    }

    }

    I’ll be posting a tutorial on my site how to do this, as it took me a while to find out myself :)

    Once I’ve made the tutorial I’ll post a quick link here if it’s ok, as a lot of people seem to be asking the same thing :)

    [Reply]

  28. Rob says:

    August 17th, 2009 at 11:45 am (#)

    @Pumpkin: You’ll need to loop through an associative array for your chosen post value array. I have posted a rather extensive tutorial on my blog on how to do this using JQuery and PHP: see http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/.

    However, if you’re familiar with PHP you’d simply use a key value approach. You need to name each dynamically added field say ‘fields[]‘ so PHP reads the POSTS data as an array E.g.

    foreach ( $_POST['fields'] as $key=>$value ) {
    echo $value , “”;
    }

    [Reply]

  29. Rob says:

    August 18th, 2009 at 3:36 pm (#)

    A short article I wrote explaining how to retreieve multiple values when you add more than one field each time – http://www.web-design-talk.co.uk/94/getting-multiple-array-form-values-with-php/

    [Reply]

  30. satheesh says:

    August 27th, 2009 at 4:44 am (#)

    how can i add form elements in dynamically created form

    [Reply]

  31. Random Randy Ramblings | DOM-inating dynamic form elements says:

    September 27th, 2009 at 9:50 am (#)

    [...] thanks to my two sources for parts of this exercise here and [...]

  32. Meghan says:

    October 10th, 2009 at 11:29 am (#)

    I have to create a form which the user can add a form field, which will be “Item ID, Quantity, and Price” and then when the user has entered all the information, they can press “process order” and an alert box will pop up saying the total order.

    I cant figure out how to get the process order function to multiply the quantity and price of each line seperatly, and then add them together.. It will only do it for one line, the parentnode, i think its because i cant figure out how to give the elements that are created a unique ID.

    here is the code i have so far, any help would be greatly appreciated

    function addKeyword()
    {
    var keywordObj = document.getElementById(“keywordForm”);
    var count = document.getElementById(“keywordCount”).value;
    var newObj = document.createElement(“div”);
    newObj.setAttribute(“id”, “keywordInput_” + count);
    newObj.innerHTML = “Item ID: ” + ” ” +
    “Quantity: ” + ” ” + “Price: $ ” + ” ” + ” “;
    keywordObj.appendChild(newObj);
    count++;
    document.getElementById(“keywordCount”).value = count;
    }

    function delKeyword(i)
    {
    var div = document.getElementById(“keywordForm”);
    var delDiv = document.getElementById(“keywordInput_” + i);
    div.removeChild(delDiv);
    }

    function ProcessOrder()
    {
    var strOutput;
    var Quantity;
    var Price;
    var TotalPrice;

    Quantity = document.getElementById(‘txtQuantity’).value;
    Price = document.getElementById(‘txtPrice’).value;
    TotalPrice = Quantity * Price;

    strOutput = “Total Price: $” + TotalPrice

    alert(strOutput);
    }

    First Name:

    Last Name:

    Item ID: Quantity: Price: $

    [Reply]

    Meghan reply on October 10th, 2009 11:31 am:

    and here is the HTML code

    First Name:

    Last Name:

    Item ID: Quantity: Price: $

    [Reply]

  33. Michael M says:

    November 3rd, 2009 at 1:07 pm (#)

    How do I control the output of the script when I have it creating mulitple fields?

    Example: If I’m asking for ^user^|^url^|^location^ and these field get mulitplied based on the number of desired submition my output ends up looking like this.

    John Mike Tom|www.test.com http://www.five.com http://www.four.com|Dallas New York Paris

    The desired output should look like this
    John|www.test.com|Dallas
    Mike|www.five.com|New York
    Tom|www.four.com|Paris

    How do I do this?

    [Reply]

    Web Design Rob reply on November 5th, 2009 4:55 pm:

    I wrote an article on exactly how to do this :)

    http://www.web-design-talk.co.uk/58/adding-unlimited-form-fields-with-jquery-mysql/

    [Reply]

  34. domina says:

    January 15th, 2010 at 2:33 am (#)

    i copied all of your codes..
    but this part is not running:

    $myInputs = $_POST["myInputs"];
    foreach ($myInputs as $eachInput)
    {
    echo $eachInput . “”;

    and got this error:
    Warning: Invalid argument supplied for foreach() in E:\programfiles\xampp\htdocs\trial\index.php on line 23

    please tell me what’s the problem..
    you can email me at:
    gondong.domina@yahoo.com

    please do help..
    tnx.

    [Reply]

  35. Kevin says:

    February 15th, 2010 at 9:09 am (#)

    Great Tutorial!! I was doing it in a roundabout way of creating ids -textarea1,2,… instead of using textarea[]… Good thing I found about this easy way ^_^”…also, Thanks to Matthew Atkins for pointing out that problem with the form tag . Got me a headache for 2 days…I wouldn’t have thought about looking for the problem in the form tag -_- . Thanks a looot guys :)

    [Reply]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets