JSFiddle - React, Tailwind, and code Playground

by Riccal

HTML

<form>
    <p>
        <label for="image">Image:</label>
        <br />
        <input type="file" name="image" id="image" />
    </p>
</form>
<div id="image_preview">
    <img src="#" />
    <br />
    <a href="#">Remove</a>

</div>

CSS

#image_preview {
    display:none;
}

JavaScript

/** 
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 () {
    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 {
        file = jQuery('#image').prop("files")[0];
        blobURL = window.URL.createObjectURL(file);
        jQuery('#image_preview img').attr('src', blobURL);
        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();
}