I'm a web developer, freelancer, author, speaker, entrepreneur, technical reviewer and blogger based in the North East, living in a village just outside of Chester-le-Street.

My blog

Add another ... with PHP and jQuery

There have been quite a few situations where I've been developing a website, and on a form needed the option to add another set of fields, for example creating an invoice - after completing the fields for the first item on the invoice, you might want to add some more.

After searching the web for possible solutions, I decided to come up with my own, and today, I thought I'd share that.

I'll explain my method using the example of an invoice system, where you would have a form to fill in for an invoices details, but may then want to keep adding new items to the invoice before submitting the form.

example

The technique is quite simple, you have a hidden field, which stores the number of invoice items that have been added. jQuery is used to increment this number, and to add a new row to the table, using the .append method, inserting the current item number to the item field names, when the add another item button is clicked. The PHP script then inserts a new entry to the invoices table, and keeps a record of the ID. A quick for-loop can then iterate through each of the submitted invoice items, and provided values were actually entered in the text fields, they can be inserted into the database.

HTML

You have a HTML form fields for the first item for the invoice, with a suffix of _1. A hidden field with a value of 1, and a button with an id of addnew to add a new item.

<table id="invoice"> 
	<tr> 
		<th>Quantity</th><th>Item</th><th>Tax rate</th><th>Unit cost</th> 
	</tr> 
	<tr> 
		<td> 
			<input type="text" id="quantity_1" name="quantity_1" /> 
		</td> 
		<td> 
			<input type="text" id="item_1" name="item_1" /> 
		</td> 
		<td> 
			<select id="rate_1" name="rate_1"><option value="1">N/A</option></select> 
		</td> 
		<td> 
			<input type="text" id="cost_1" name="cost_1" /> 
		</td> 
	</tr> 
</table> 
<input type="submit" id="record" name="record" value="Create invoice" />
<input type="button" id="addnew" name="addnew" value="Add new item" /> 
<input type="hidden" id="items" name="items" value="1" /> 

jQuery

The jQuery intercepts the clicking of the addnew button, increments the currentItem counter, creates a new row for the table, adds it by append()ing it to the table, and then updates the hidden fields value.

<script type="text/javascript"> 
	$(document).ready(function() {
		var currentItem = 1;
		$('#addnew').click(function(){
			currentItem++;
			$('#items').val(currentItem);
			var strToAdd = '<tr><td><input type="text" id="quantity_'+currentItem+'" name="quantity_'+currentItem+'" /></td><td><input type="text" id="item_'+currentItem+'" name="item_'+currentItem+'" /></td><td><select id="rate_'+currentItem+'" name="rate_'+currentItem+'"><option value="1">N/A</option></select></td><td><input type="text" id="cost_'+currentItem+'" name="cost_'+currentItem+'" /></td></tr>';
			$('#invoice').append(strToAdd);
			
		});
	});
</script> 	

PHP

Finally, when the form is submitted, our PHP code first creates the invoice record, and then for each new row created, checks to see if the fields were filled in, and if so, creates an invoice item, referencing the invoice ID it is part of.

// after creating an invoice record in the invoice table
$invoice = mysqli_insert_id( $link );
for( $i = 1; $i <= $num; $i++ )
{
	if( isset( $_POST['quantity_' . $i] ) && isset( $_POST['cost_' . $i]) && intval( $_POST['quantity_' . $i] ) > 0 )
	{
		$rate = intval( $_POST['rate_' . $i ] );
		$qty = intval( $_POST['quantity_' . $i] ) ;
		$cost = mysqli_real_escape_string( ( is_numeric( $_POST['cost_' . $i] ) ? $_POST['cost_' . $i] : intval( $_POST['cost_' . $i] ) ) );
		$item = mysqli_real_escape_string( $_POST['item_' . $i ]);
		$sql = "INSERT INTO invoice_items (`invoice`, `quantity`, `item`, `cost`, `tax`) VALUES ( {$invoice}, {$qty}, '{$item}', '{$cost}', '{$rate}' )";
		mysqli_query( $link, $sql ); 
	}
}

JavaScript not enabled?

If the user doesn't have JavaScript enabled (I primarilly use this solution in admin areas, where JavaScript is required), you could either hide the button, and require the user to create the first set of items, and repeat, or alternatively, have the button insert the first set, and then redirect the user to a page where they can add another item.

Donate

Like this code, want to give me some pennies?

Posted by Michael on 22nd Apr 2010 at 11:11

Comments

I read on the Google Speed blog the other day a great way to perform multiple INSERT queries. Instead of placing them in a loop as above, create the values array in the loop. For example: Hopefully you can see what I'm trying to demonstrate from the snippet above. Basically, it would produce a SQL query similar to: INSERT INTO tbl_name (name,email) VALUES ('Martin','martin@example.com'), ('Michael','michael@example.com')

Posted by Martin Bean on 22nd April 2010 at 15:03

Bugger! My code example was stripped!

Posted by Martin Bean on 22nd April 2010 at 15:03

Thanks for the comment Martin, you are right that is a better way to do it - but for the example code I couldn't be bothered to do it that way! Normally, I'd have an array of inserts, and within the loop, just add to that array, then once the loop had completed, pass the array to my database object which would turn it into a single query, and execute it.

Posted by Michael Peacock on 22nd April 2010 at 15:03

Sounds funky! I have yet to put the above theory into practice myself, like.

Posted by Martin Bean on 22nd April 2010 at 15:03

Actually Mr.Peacock, I feel you really should be using PHP\'s natural form handling techniques. :) HTML Markup: http://pastie.org/930017 PHP Handling: http://pastie.org/930023 Yours, smugly, Anthony.

Posted by Anthony Sterling on 22nd April 2010 at 17:05

Thanks Anthony - strangely, I didn't realise you could treat fields like that as an array (I know you can with checkboxes), and that jQuery you posted is rather neat - thanks for sharing!

Posted by Michael Peacock on 22nd April 2010 at 19:07

this post has used relCopy.js jquery plugin. It also ads a feature(a link) to remove the added field. http://www.9lessons.info/2010/04/jquery-duplicate-field-form-submit-with.html

Posted by kiran aghor on 28th April 2010 at 07:07

Thanks for your post. I like your idea. It's simple and easily to be understanded. But why i cannot get nothing when submit form except the first row with id and nam _1 ?

Posted by Sugeng Prasetyo on 26th June 2010 at 19:07

Have you tried echo '' . print_r( $_POST, true ) . ''; so you can see all of the postdata which is being submitted.

Posted by Michael Peacock on 30th June 2010 at 12:12

you can also refer to this site on how to duplicate fields with jQuery plugin in just a few line of javascript code. http://www.ryscript.co.cc/jQuery/jQuery-duplicate-fields-form-submit-with-php/ thanks

Posted by rys on 15th July 2010 at 05:05

jj

Posted by u on 22nd July 2010 at 11:11

I'll put him on rape bbs rape 3366

Posted by Gflyofxj on 3rd September 2011 at 21:09

Could I take your name and number, please? free pics teen porn 07644

Posted by Ondqpabi on 6th September 2011 at 09:09

Do you know the number for ? underage thai girls leg

Posted by Nydxykhu on 7th September 2011 at 12:12

I can't get a signal sandra model bbs %-))

Posted by Mohwdqxs on 7th September 2011 at 19:07

Add a comment