Papermashup

Subscribe


Tweets


"RT @Eva_Shaughnessy: #finedining @romomobilecafes restaurant this evening with #NewHair #winning #SaturdayNight #GirlsNightOut http://t.co/…"

@ashleyford 2 weeks ago

"RT @kycutwilson: @ashleyford @burgerbeartom incredible. There's 5 more left! Shout about it!!"

@ashleyford 4 weeks ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Papermashup

Dynamically adding form inputs and using jQuery

Add and submit form inputs on the fly using JavaScript

AshleyAshley

You may find a need to allow the user to dynamically add or remove text inputs from your application. This is relatively easy to do using jQuery and using arrays to submit the form data to a PHP page. This tutorial runs through setting up the form with the controls to add, remove and reset the form fields as well as preparing the form variables to be sent using AJAX.

The Code

You won’t need to be a JavaScript master to work out what’s going on here. the first click functions control the number of input fields displayed on the page. Each new input field that’s added is given the ‘dynamic[]’ array name so the values are concatenated and separated with a comma.

Then once the user submits the form, the form values are pushed into an array which can then be submitted using PHP to your database. You’ll probably need to either store the complete string for example 1,2,3,4,5,6,7 in the database or explode the string using PHP where you can manipulate it further.



$(document).ready(function(){

var i = $('input').size() + 1;

$('#add').click(function() {
$('<div><input type="text" class="field" name="dynamic[]" value="' + i + '" /></div>').fadeIn('slow').appendTo('.inputs');
i++;
});

$('#remove').click(function() {
if(i > 1) {
$('.field:last').remove();
i--;
}
});

$('#reset').click(function() {
while(i > 2) {
$('.field:last').remove();
i--;
}
});

// here's our click function for when the forms submitted

$('.submit').click(function(){

var answers = [];
$.each($('.field'), function() {
answers.push($(this).val());
});

if(answers.length == 0) {
answers = "none";
}

alert(answers);

return false;

});

});

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 23
  • Kingsley
    Posted on

    Kingsley Kingsley

    Reply Author

    Hello very nice tutorial i really gained alot from this but please if how to use jquery validate to validate the fields how will i do it please.


    • Cesar Bielich
      Posted on

      Cesar Bielich Cesar Bielich

      Reply Author

      You dont need jquery to validate fields, HTML5 already does this and its built right into it. If you have a text field all you have to do is ad “required”. Here is an example

      <input type="text" name="example" required


  • Andres Silva Arias
    Posted on

    Andres Silva Arias Andres Silva Arias

    Reply Author

    how to manipulate this dinamic fields with php dinamically


  • Zaheer
    Posted on

    Zaheer Zaheer

    Reply Author

    i want add fix dynnmic field and also want to fix therer name
    for example

    to name =a12

    and

    to name =b12

    how its posible


  • adira
    Posted on

    adira adira

    Reply Author

    What’s up, yes this post is in fact fastidious and I have learned lot of things from it concerning blogging. thanks.


  • tert
    Posted on

    tert tert

    Reply Author

    dsd


  • Immigration Solicitor folkstone
    Posted on

    Immigration Solicitor folkstone Immigration Solicitor folkstone

    Reply Author

    Hola! I’ve been following your website for a long time now and finally got the courage to go ahead and give you a shout out from Lubbock Tx! Just wanted to say keep up the great job!

    Also visit my weblog Immigration Solicitor folkstone


  • Rusty
    Posted on

    Rusty Rusty

    Reply Author

    You’ll encounter a change in your lifestyle after undergoing this bariatric surgery. Many surgeries can be expensive and can involve challenging lifestyle changes, particularly after lap-band surgery and other bariatric procedures. Then it was off to enrolling in the Silver Hill Psychiatric Hospital in New Canaan, Connecticut.


  • jyothi
    Posted on

    jyothi jyothi

    Reply Author

    Its fine good.. but how can i validate these dynamically added fields.. can any one help me out…


  • http://tinyurl.com/afribeirn13046
    Posted on

    http://tinyurl.com/afribeirn13046 http://tinyurl.com/afribeirn13046

    Reply Author

    I Feel post, “Dynamically adding form inputs and submit using jQuery | Papermashup.
    com” was in fact spot on! I personallycannot see eye to
    eye with u even more! Finally looks like I personallyuncovered a blog definitely worth
    reading through. Thanks for your time, Heather


  • Eun Woo
    Posted on

    Eun Woo Eun Woo

    Reply Author

    How to I make more than one of these boxes with different attributes so I can PHP post it individually?!?!

    by the way, in order to validate this with PHP, use this:

    <?php
    foreach($_POST['dynamic'] as $value) {
    echo "$value “; // change this to what you want to do with the data
    }
    ?>


  • college
    Posted on

    college college

    Reply Author

    Hi,

    What should i do if I want to delete/insert a row/element in the middle? I would like to have a + and – sign so that I can insert / delete element in the middle.


  • shahab
    Posted on

    shahab shahab

    Reply Author

    thx, wish you had told us how to retreive the information by PHP. I have a problem finding out how to send the values to a PHP page by POST, as you use the submit button for another purpose …


  • gentjana
    Posted on

    gentjana gentjana

    Reply Author

    I saw the example of “Dynamically adding form inputs and submit using jQuery” and it is great, but i’d like to see another example how to add and remove input fields using AJAX and submit data into db.

    Thanks.


  • amal
    Posted on

    amal amal

    Reply Author

    very useful and very nice article thank you


  • veeraselvam
    Posted on

    veeraselvam veeraselvam

    Reply Author

    Hi! Your scripts work fine. but this script only get value using javascript. I want how to get value using PHP for Dynamically adding form inputs.


  • rockstar
    Posted on

    rockstar rockstar

    Reply Author

    very good script but would be better if it would validate the fields as well and also explain how to retrieve those textbox values from server side language like php.
    i’ve found a tutorial at

    http://www.pradipchitrakar.com.np/blog/dynamically-add-remove-textfield.html

    it explains how to dynamically add, remove and validate text field in jquery and fetch the values of textbox in php and jsp/servlet


  • cruisine
    Posted on

    cruisine cruisine

    Reply Author

    yeah..it’s work fine here…but i have the same question like João Carlos …how can i use form validation?on my script the validation rule only recognize the field with name=”dynamic” and not “dynamic[0]…bla..bla..bla”
    need ur help soon..
    thank u..


  • João Carlos
    Posted on

    João Carlos João Carlos

    Reply Author

    Use the array index.
    field1 = dynamic[0]
    field2 = dynamic[1]

    and so on…


  • Pablo
    Posted on

    Pablo Pablo

    Reply Author

    Hello, i’m using this tutorial to save in a mysql database. But i dont know how to save this added fields in different rows of a table. One row for each value.


  • João Carlos
    Posted on

    João Carlos João Carlos

    Reply Author

    Hi! Your scripts work fine here… But how can I use the validate and maskedinput JQuery scripts with this solution?
    I need to validate de dynamic inputs and maybe put a mask on it. Maybe you can help!