"Add Another" - jQuery Plugin

Following from one of my earlier posts, "Add another ... with PHP and jQuery", I decided to create a jQuery plugin to make future implementations of this feature easier. This is my first jQuery plugin, and I was pleasantly surprised at how simple it was to create one, the documentation was very helpful.

I'm planning on improving it (so please let me know your suggestions) and working on a separate one which takes values from a separate form, and puts the data into a new row on a table (same functionality as this, just getting the jQuery to clone and populate based off values elsewhere).

What does it do?

It assumes you have a table, with at least one row containing a number of form fields which you would fill in, and possible duplicate to create new entries (illustrated from my invoicing system example in my earlier post). It also adds delete functionality for the rows.

How it works

You call the plugin from a button on the page, passing the table ID as a paramater. The plugin adds functionality to a "delete" link on the one existing row on the table, and binds to the buttons onclick action.

Depending on the tables structure, i.e. if it uses <thead> for its headings, or (as supplied by a configuration variable) if it doesn't and also doesn't make use of the first row of the table for headings, it clones the first row that you would want to clone.

Usage

 
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.addanother.js"></script>
</head>
	<body>
	<form action="http://localhost/showpostdata.php" method="post">
	<table id="test-table">
		<thead>
			<tr>
				<th>Field</th><th>Delete</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td><input type="text" name="row[0][field]" /></td><td><a href="#" class="deleterow">Delete</a><td>
			</tr>
		</tbody>
	</table>
	<input type="submit" />
	</form>
	<input type="button" id="test-button" />
	<script type="text/javascript">
		$(document).ready(function(){
			$('#test-button').addanother( '#test-table' );
		});
	
	</script>
	</body>
</html>

Code

 
/**
 * jQuery "Add Another" Plugin v1.0
 * @author Michael Peacock
 * @url www.michaelpeacock.co.uk
 * 
 * Thanks to Anthony Sterling, for his initial comments on: http://www.michaelpeacock.co.uk/blog/entry/add-another-item-with-php-and-jquery
 *
 */
(function($) {
 
	$.fn.addanother = function(table, settings) {
		
		var config = {'deletelink' : 'deleterow', 'usesheading' : true };
		
		var usestbody = ( $(table).find('thead').size() == 1 ) ? true : false;
 
		if (settings) $.extend(config, settings);
		
		// for the existing row in the table
		$('.' + config.deletelink).click(function(){
			$(this).closest("tr").remove();
			return false;
		});
		
		// click: add another
		$(this).click(function(){
			
			// duplicate the row, replace[0] with [number of rows -1] and clear the input values; use usestbody and usesheading to work out how many rows are in use! 
			$(table + ( (usestbody) ? ' > tbody > tr:first-child' : (config.usesheading) ? ' tr:eq(1)' : ' tr:first-child' ) ).clone().appendTo(table + ((usestbody) ? ' > tbody' : '') ).find('input').each(function(index, input){
                        $(input).attr('name', function(index, attr){
                            return attr.replace('[0]', '[' + ( $(table + ( (usestbody) ? ' > tbody' : '' ) ).find('tr').size()-(usestbody ? 1 : config.usesheading ? 2 : 1 )) + ']');
                        }).attr('value', null);
                    });
			// for cloned rows in the table
			$('.' + config.deletelink).click(function(){
				$(this).closest("tr").remove();
				return false;
			});
		
		});
 
		return this;
		
	};
 
})(jQuery);

Special Thanks

Special thanks goes to Anthony Sterling, for his contribution in the comments on my previous post about this, showing how to improve upon my initial method.

Posted by Michael on 17th Jul 2010 at 12:12

Comments

Nice share just what I was looking for thanks dude!

Posted by ainslie johnson on 4th August 2010 at 10:10

For anyone interested, I've just modified the code for this to add a callback called 'afterAdd' as I found that I lost event associations on added rows: http://pastie.org/1155863

Posted by Rich Milns on 13th September 2010 at 16:04

Thanks for sharing your improvements Rich.

Posted by Michael Peacock on 20th September 2010 at 21:09

this is the first time come to your blog.thanx your sharing.

Posted by abercrombie on 17th February 2012 at 06:06

Metformin Diabetes Prevention Lifestyle Intervention Social Cognitive Theory Weight Loss Meteoxane Online Consultation Tramadol Tr50 Drugs. Metamucil And Lisinopril Motrin Maximum Daily Dosage Dr Varon's Vitamin C Concentrated Products Rxlist Motrin Ibuprofen . Prochlorperazine No Prescription Us Tikosyn And Augmentin . Diabetes Mellitus Type2 Insulin Lispro Metoprolol Tartrate Tb24 Cheap Tramadol Get A Medical Fast Delivery Aace Diabetes Nets Order Lida Daidaihua Casserole For La Weight Loss Juice Phenergan And Pain Effects Ciplox Buy Europe, Buy Ciplox Online In Florida Buy Zoloft Now, Zoloft Generic Pill Galantamine Online No Prescription Mastercard, Buy Galantamine Online Cod Overnight Zoloft Saturday Delivery Mastercard, Can Buy Zoloft Online Legally Next Day Delivery Vermox With No Script, Buy Vermox In Belfast Buy Cheap Aberela Cod, Aberela Online Cash On Delivery Buy Ventolin, Ventolin By Echeck Ampicillin Price Uk, Ampicillin Online Cheap Buy Zithromax Pay Cod, Cheap Zithromax Pay Uss Online Us Seroquel, Online Apotek Seroquel Purchase Asendin Mastercard, Buy Asendin Us Pharmacy Online Ciplox Order Online, Ciplox Online Overnight Delivery

Posted by Zosyboype on 4th January 2014 at 14:02

Post a comment