In one of my forms I have an input field for image uploads in WordPress. Also I have a jQuery script that preview the selected image before upload and add a Remove link for this preview. This works very well if they are in one file (a plugin), but the Remove link doesn’t work if the jQuery script is enqueued in a separate JS file, it just sends to the top of the page. Why this happens?
I tried to add an event.preventDefault();
as below, but this doesn’t helped:
jQuery('#image_preview a').bind('click', function (event) {
event.preventDefault();
....
The CSS/HTML part:
<style>
#image_preview {
display: none;
}
</style>
<input type="file" name="image" id="image" class="image"/>
<div id="image_preview">
<img src="#" id="image-preview" style="width: 100px; height: 100px;" /><br />
<a id="image_remove" href="#">Remove</a>
</div>
The jQuery part:
/**
onchange event handler for the file input field.
* It emplements very basic validation using the file extension.
* If the filename passes validation it will show the image
using it's blob URL and will hide the input field and show a delete
button to allow the user to remove the image.
*/
//jQuery('#image').on('change', function () {
jQuery( document ).delegate('#image', 'change', function() {
ext = jQuery(this).val().split('.').pop().toLowerCase();
if (jQuery.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
resetFormElement(jQuery(this));
window.alert('Not an image!');
} else {
var reader = new FileReader();
var image_holder = jQuery("#"+jQuery(this).attr('class')+"-preview");
image_holder.empty();
reader.onload = function (e) {
jQuery(image_holder).attr('src', e.target.result);
}
reader.readAsDataURL((this).files[0]);
jQuery('#image_preview').slideDown();
jQuery(this).slideUp();
}
});
/**
onclick event handler for the delete button.
It removes the image, clears and unhides the file input field.
*/
jQuery('#image_preview a').bind('click', function () {
resetFormElement(jQuery('#image'));
jQuery('#image').slideDown();
jQuery(this).parent().slideUp();
return false;
});
/**
* Reset form element
*
* @param e jQuery object
*/
function resetFormElement(e) {
e.wrap('<form>').closest('form').get(0).reset();
e.unwrap();
}
This is how the jQuery script is enqueued:
function the_plugin_scripts() {
wp_enqueue_script( 'images-preview', plugins_url( 'js/images_preview.js' , __FILE__ ), array('jquery') );
wp_localize_script( 'images-preview', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'the_plugin_scripts' );
See a working demo on JSFiddle.