Contact Us

6ta. Avenida 2-48 zona 13, Guatemala, Guatemala.

T +(502) 2458-4464 • Email: info@pixtig.com

Write us :)

Quote
Your budget in US Dollars ($)
Current Website (if you have one)
I want to be part of your team
Inquiry
Can you help us?

Blog

We are passionate about Drupal and obsessed with adding significant content to the web. We design, we program, we develop, we comunicate, we teach and blogging.

jorge's picture

Replacing fields of type "file"

By: 
jorge
Tags: 
Javascript
Input
File

Surely we have seen in the situation that in the design of an application or website, change the style of the input file type.

In this small article we will see a simple way to solve this easy problem using javascript.

Then the script. (it is discussed and it is simple to know what each line)

Código: 
var $ = jQuery.noConflict();
$(document).ready(function() {
	/**
     * Search the input file type and
      * Replaced by an image that triggers the input file
 	 * you only need to add the "filetype" class to container elements
 	 * img.typeFile and span.fileDir and the input file to be replaced.
 	 *
 	 * Example structure:
 	 * ------------------------------------------------------------------------------------------
 	 *
 	 * <div class="form-item filetype">
     *     <label class="labelform">Foto
     *      <span class="small">Image JPG or PNG</span>
     *    </label>
     *      <img class="typeFile" src="template/images/agregar.png"><span class="fileDir"></span>
     *      <input type="file" name="archivo" class="form-file"/>
     * </div>
     */
    $('div.filetype').each(function(f) { // each of the parent elements (see example above)
        $(this).find('input[type="file"]').addClass('file-' + f); // Assigning a dynamic class
        $(this).find('input[type="file"]').css('cssText', 'display:none;'); // Disabling the file type inputs within the form.
        $(this).find('img.typeFile').on('click', function() { // Click Event Trigger input type file (an image or a button, depending on their design)
        $(this).css('cssText', 'opacity:1;'); // Simple effect opacity
        $(this).parent().find('input[type="file"]').trigger('click'); // Element running the input file type is hidden
            $(document).delegate('.file-' + f, 'change', function() { // Looking for a change in the input file type
                if (this.value == "") {
                    /* Search if the input is empty and assigns default */
                    $(this).parent().find('.fileDir').html('<span style="color:#D0D0D0;">nothing selected.</span>');
                } else {
                    /* If a value selected by the user, obtains and displays it in a span tag with the class "fileDir" */
                    $(this).parent().find('.fileDir').html(this.value);
                    $(this).parent().find('.fileDir').css('cssText', 'color:#000;');
                };
            });
        });
    });
});