Use your left/right keys to browse tutorials
Dynamically adding form inputs and submit using jQuery

Dynamically adding form inputs and submit using jQuery

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on September 8, 2010

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;
								
	});
	

});




Recent shares

More tutorials from Papermashup
Comments
17 discussions around Dynamically adding form inputs and submit using jQuery
  1. 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

  2. Pingback: Dynamically adding form inputs and submit using jQuery

  3. Rusty says:

    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.

  4. jyothi says:

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

  5. 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

  6. Eun Woo says:

    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
    }
    ?>

  7. college says:

    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.

  8. shahab says:

    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 …

  9. gentjana says:

    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.

  10. amal says:

    very useful and very nice article thank you

  11. Pingback: Dynamically adding form inputs and submit using jQuery | Tech Blog

  12. veeraselvam says:

    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.

  13. rockstar says:

    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

  14. cruisine says:

    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..

  15. João Carlos says:

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

    and so on…

  16. Pablo says:

    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.

  17. João Carlos says:

    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!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.