[ close ]
Help Upgrade the Web: Download Firefox 3.6

jQuery Dynamic Form

jQuery Dynamic Form is a plugin for jQuery. It gives the ability to dynamically add fields based on HTML template.

Links

Code

All #something are references to the node element ids in the HTML dource code.

$(document).ready(function(){  
    $("#duplicate").dynamicForm("#plus", "#minus", {limit:5});
    $("#duplicate2").dynamicForm("#plus2", "#minus2", {limit:4});
    $("#duplicate3").dynamicForm("#plus3", "#minus3",
        {
            limit:3,
            createColor: 'yellow',
            removeColor: 'red'
        }
    );
});

NB : The color effects of the third demo requires the jQuery UI Highlight Effect Module

Demo

#duplicate + and - are outside the duplicated node

[-] [+]

#duplicate2 + and - are inside the duplicated node

[-] [+]

#duplicate3 Multiple fields duplication

Address

[-] [+]

  • Share/Bookmark

38 comments

  1. I’m having trouble implementing this jQuery plugin for dynamic forms while following this tutorial. There are no errors on firebug but the ‘+’ & ‘-’ options are not seen on the page:

    HTML:

    ………..

    $(document).ready(function(){
    $(‘#duplicate’).dynamicForm(‘#plus’, ‘#minus’, {limit:2});
    });

    Is there something that I’m missing?

  2. HI,
    Any ideas on how you might then send this information via email?

    Cheers, Wes

  3. Thats nearly what I’m looking for.
    Ist it possible to make “nested” fieldsets?

    So add the a address record and have inside each of these the possibility to add one to five phone numbers?

    best regards
    ludwig

  4. I think my last comment didn’t got through because there are some lines of example code included.

    This simple target is not sufficient because it generates the same id “plus” in each generated block. So this id exists more than once. Each generated block should contain a new id for the plus-sign.

    Any idea?

    Best regards
    Ludwig

    • @Ludwig You can use any CSS selector for the plus and minus selection. So instead of using id’s you would better choose class. Thus it would give :

      $("#phonenumber").dynamicForm("#phonenumber .plus", "#phonenumber .minus", {limit:5});
  5. Thank you for the tipp. Now I have to concetrate on an other project but I will be back in a few days to solver this task.

    Best regards
    Ludwig

  6. It’s what i was looking for but… it’s hard to do a server side script reading all these fields with strange IDs.
    Any suggestions?

  7. Thanks Stéphane

    To clarify my question. I was really wondering how to send it via email given that all of the new dynamically created values (class/id/name) are unknown. I have only had experience creating forms that require this data to be known before sending.

    Have you got any suggestions for scripts that will pick up the dynamic data and send it via email?

    Cheers, Wes

    • @Wes Look at the name attribute of the duplicated field. Before its get duplicated it has the form of :

      <input type="text" size="30" name="phone" id="phone">

      You collect them as a simple variable server side. phone is a variable.

      As soon as it is duplicated the name attribute change to the form of

      <input type="text" size="30" name="phone[]" id="phone0">
      <input type="text" size="30" name="phone[]" id="phone1">

      You collect them as an array of variables server side. phone becomes an array of variables.

      • It’s easy for one field…
        Multiple fields duplication has some problem associating fields (address1 with postalcode1…).
        Why don’t you use the “name” this way? name=”form[1][address]“…..

        Have you a solution for script 3 server side?
        Thanks

        • Tell me if I’m wrong but can’t you just loop over the array, fields are ordered by indexes :

          for ($i = 0; $i < count($_REQUEST["adr3"]); $i++) {
              echo $_REQUEST["adr3"][$i]." / ".$_REQUEST["postal_code3"][$i]." / ".$_REQUEST["ville3"][$i]."<br>";
          }
  8. I was wondering the same thing. If the field name=”example” what would the duplicated field names be if they are an array? I tried example1, example2 etc….no luck. I process the form with only the originals and it processes fine and echo
    s the data, but if I duplicate once and submit the original fields echo array and the duplicates come up blank….

  9. So is phone collected as:

    $phone = $_REQUEST['phone'] ;
    $phone1 = $_REQUEST['phone1'];
    etc……
    ???

    • No :

      var_dump($_REQUEST["phone"]);
      $phone0 = $_REQUEST["phone"][0];
      $phone1 = $_REQUEST["phone"][1];
      $phone2 = $_REQUEST["phone"][2];
      ...
      • Please correct me if I am wrong, but if a user clicks to add and then clicks to subtract and then repeats the process of adding.. the numbers fall out of sync, it jumps to the next number in the range. That is how it appears to me. Do I have that right?

        • Actually the IDs jump of a range but server side you use the NAME attribute which should remain the same whatever the interaction.

          • Hi Stéphane

            I get that now. Sorry I am a bit thick.

            So my question now is what if I have a group and they need to sit in order and stay associated with their particular group… and each group is a duplicated group. Example..

            Name
            Address
            Phone

            Name
            Address
            Phone

            Name
            Address
            Phone

            Am I able to send them that way, so that they are in their particular groups?

            Cheers, Wes

  10. Hello,
    I was wondering if there was a method to remove all duplicated form elements at once? I have a form that submits info (AJAX), then resets the form, but all duplicated elements remain (although it does reset the duplicated fields). I’d like to to revert back to the pre-duplicated state, but I’mhaving trouble figuring out how.
    Thanks for any suggestions!
    -Josh

    • There is no built-in method to achieve a remove all. You can try to simulate multiple click on the minus sign though :

      var minus = $("#minus3");
      while(minus.css("display") != "none"){
          minus.click();
      }
      • That code makes sense, but I think I’m still overlooking something because I couldn’t get it to work. When an element is cloned, is it still referred to by it’s original ID, or is each cloned [-] given a new unique ID? After some trial and error, I figured it out! I just added a class to each [-] element called “click-minus”, and then added the code $(‘.click-minus’).click(); into my submit function and viola, it worked! Not even necessary to loop, as it will apply to all elements with that class. Thanks so much for the great functionality and help!

  11. I have everything working. But if I do not add any extra fields and fill in the original and send the output is broken up and distributed to the other duplicate variables. Example, if I insert into the original phone field, lets say 123-4567, it will send parts of that entry to $_REQUEST['phone'][1] and $_REQUEST['phone'][2] variables instead of sending it to $_REQUEST['phone'][0]. Any reason why?

    • I can’t reproduce it. Could you provide a link ?

    • I don’t know if this will help, but I use a function to handle the returned form data. If it is an array (such as is returned by the duplicated form elements), it passes each item in the array back into the function. Here is a simplified version of the code..

      function form_to_db()  {    // loop through submitted data and pass
                                  // into  form_to_db_check_field function
          $datarray = NULL;
          foreach($_REQUEST as $key=>$value) {
              $datarray = $this->form_to_db_check_field($key,$value,$datarray);
          }
          return $datarray;
      }
      function form_to_db_check_field($key,$value,$arr){
          if (is_array($value)){
              foreach($value as $form_count=>$form_val){
                  $key.=$form_count;  //unique name
                  $arr = $this->form_to_db_check_field($key,$form_val,$arr);
              }          
          } else {
              // code that decides if it is necessary to add $key
              //to returned array and manipulate it before it does
              $arr[$key] = $value;
          }
          return $arr;
      }
  12. J’essaie de dupliquer une fieldset en entier mais aussi pour chacun de ces fieldset, dupliquer un p interne. Toutefois, le plugin ne se comporte pas comme prévu.

    <fieldset class="even dynEtablissement">
    <p>
    <label for="etablissement" >&Eacute;tablissement <em>*</em></label>
    <select id="etablissement" name="etablissement[]" >...</select>
    <span class="inline">
    <a class="delLink minus1" href="">[-]</a>
    <a class="addLink plus1" href="">[+]</a>
    </span>
    </p>
    <p>
    <label for="url">URL du programme <em>*</em></label>
    <input id="url" class="text" type="text" name="url[]">
    </p>
    <p class="dynLieu">
    <label for="lieu">Lieu <em>*</em></label>
    <select id="lieu" name="lieu[]" >...</select>
    <span class="inline">
    <a class="delLink minus2" href="">[-]</a>
    <a class="addLink plus2" href="">[+]</a>
    </span>
    </p>
    </fieldset>
  13. So far i have everything fine, now i want to edit the form with the posted data for example there are phone fields
    phone0
    phone1
    phone2
    i want to load page with 3 phone fields visible and populated with data.

    thanks for help

    • This feature has been asked once but I have not implemented it yet.

      Is this feature interesting other ? Vote please !

      • Hi Stéphane

        Thanks to your excellent script i have developed a series of forms using dynamic forms.

        As requested earlier i need provision to pre load clones on load and normalize id if some one add further.

        Please HELP consider my special vote.

        Thanks

  14. Hi Stéphane,

    great script, I really like that’s what I was looking for. But a short question: is it possible to insert a new element between two existing?
    I mean, I use this script for fieldsets. I duplicate them, but what if I want a third fieldset after the first fieldset?

    Greets,

    Peter

  15. Josh’s comment should help, shouldn’t it ?

Leave a comment