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

});




More tutorials from Papermashup
  • Andres Silva Arias

    how to manipulate this dinamic fields with php dinamically