Thursday, June 28, 2012

jQuery input file change layout

This jQuery plug in is used to modify the style of you input file layout.

html:
<div id="cont">
        <input type="file" class="fileUpload">  
</div>

jQuery:
<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery(".fileUpload").fileUploadChange({
            image:'images/browseImg2.jpg'
        });
    });   
</script>

This is the jquery plug in.
(function($){
    $.fn.fileUploadChange = function(options){   
        // the default options
        var defaults = {   
            image:'images/browseImg.jpg'
        }           
        // to override the defaults of each option
        var options = $.extend(defaults, options);
        return this.each(function(){   
            // hides the input file
            var x=$(this);
            $(this).css({"position":"absolute","top":"-100px"});           
            // add the dummy input text and button image
            $(this).after("<input type='text' class='dummyInputText' readonly='readonly'><img class='dummyButton' src='"+options.image+"'>");
           
            // triggers the input file when the dummies are clicked
            $(".dummyInputText, .dummyButton").live("click",function(){
                $(".fileUpload").trigger("click");   
                $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());                
                if($.browser.msie || $.browser.chrome){
                    getIEvalue();
                }
                else{
                    getValue();
                }
            });
           
            // this function gets the value of input file and displays in the dummy
            function getValue(){
                setInterval(function(){
                    var value=$(".fileUpload").val();       
                    $(".dummyInputText").val(value);
                },100);
            }
           
            // this function gets the value of input file and displays in the dummy IE or CHROME
            function getIEvalue(){
                setInterval(function(){
                    var value=$(".fileUpload").val();
                    value=value.replace(/[/\\*]/g, "/");
                    var xvalue=value.split("/");
                    var l=xvalue.length;
                    var ievalue=xvalue[l-1];
                    $(".dummyInputText").val(ievalue);
                },100);
            }
        });   
    };
})(jQuery);

Hope this will help!..