WP-Mix

A fresh mix of code snippets and tutorials

jQuery Add Another Image Link

This code snippet is taken from my plugin, User Submitted Posts. It displays a link that users may click to add another file-upload input field.

Step 1: The Markup

Here is the basic HTML that we’ll need for the script to work:

<input class="hidden" type="hidden" name="usp-image-limit" id="usp-image-limit" value="<?php echo $usp_options['max-images']; ?>">
<input class="hidden" type="hidden" name="usp-image-count" id="usp-image-count" value="1">

This creates two hidden fields that provide the following information:

  • The image input limit, provided by usp-image-limit
  • The current image count, provided by usp-image-count

The form may include whatever other fields and/or markup is required, but must include these hidden fields. Additionally, the form must include the “add another image” link and a file-input field. For example:

<div class="usp-images">
	<input type="file" name="image">
	<a id="usp_add-another" href="#">Add Another Image</a>
</div>

This gives us the container <div> that will contain the cloned file inputs. It also provides the original file input (used for cloning), and the “add another image” link. All of these factors come into play in the next step.

Step 2: The JavaScript

With the HTML included in your form, add the following jQuery function to enable the “add another image” functionality:

jQuery(document).ready(function($) {

	// add another image
	var x = parseInt($('#usp-image-limit').val());
	var n = parseInt($('#usp-image-count').val());
	if (x == 1) {
		$('#usp_add-another').hide();
	}
	$('#usp_add-another').click(function(event) {
		event.preventDefault();
		n++;
		var $this = $(this);
		var $new = $this.parent().find('input:visible:last').clone().val('');
		$('#usp-image-count').val(n);
		if (n < x) {
			$this.before($new.fadeIn(300));
		} else if (n = x) {
			$this.before($new.fadeIn(300));
			$this.hide();
		} else {
			$this.hide();
		}
	});
});

No editing is required, this should work out of the box. Basically what we’re doing here is grabbing the image limit and count data, and then cloning the file input field whenever the #usp_add-another link is clicked. When the file limit is reached, the add-another link will be hidden from the user.

Note that if you use this technique it is important to include proper server-side validation and file checking (i.e., don’t rely on JavaScript as it can be disabled by the user).

To see this script in action, check out User Submitted Posts or USP Pro!

★ Pro Tip:

Banhammer ProWizard’s SQL Recipes for WordPressSAC Pro