This simple JavaScript code styles all file inputs to match with Bootstrap's style.
Simply, it turns this:
Into this input:
(function(window){
window.jQuery(function($){
$('input[type="file"]').each(function(){
var $this = $(this);
var $parent = $this.parent();
$this.detach();
$parent.prepend(
$('<div id="' + $this.attr('id') + '_input-group" class="input-group">' +
'<label class="input-group-btn" for="' + $this.attr('id') + '">' +
'<span class="btn">' + ($this.attr('data-label') || 'New image:') + '</span>' +
'</label>' +
'<input id="' + $this.attr('id') + '_path" type="text" class="form-control" readonly="readonly">' +
'<label class="input-group-btn" for="' + $this.attr('id') + '">' +
'<span class="btn btn-primary">' +
($this.attr('data-button-label') || 'Browse') +
'<div style="display:none;"></div>' +
'</span>' +
'</label>' +
'</div>')
);
$this.appendTo('#' + $this.attr('id') + '_input-group label:last-child div:last-child');
var $path = $('#' + $this.attr('id') + '_path', $parent).click(function(){
$this.click();
});
$this.bind('change.input_file_styler', function(){
$path.val(this.files[0] ? this.files[0].name : '');
});
});
});
})(Function('return this')());
I really can't put my finger on what's wrong... but I know that something is stinking in there!
What can I improve in this code?
If you want to try it out:
(function(window){
window.jQuery(function($){
$('input[type="file"]').each(function(){
var $this = $(this);
var $parent = $this.parent();
$this.detach();
$parent.prepend(
$('<div id="' + $this.attr('id') + '_input-group" class="input-group">' +
'<label class="input-group-btn" for="' + $this.attr('id') + '">' +
'<span class="btn">' + ($this.attr('data-label') || 'New image:') + '</span>' +
'</label>' +
'<input id="' + $this.attr('id') + '_path" type="text" class="form-control" readonly="readonly">' +
'<label class="input-group-btn" for="' + $this.attr('id') + '">' +
'<span class="btn btn-primary">' +
($this.attr('data-button-label') || 'Browse') +
'<div style="display:none;"></div>' +
'</span>' +
'</label>' +
'</div>')
);
$this.appendTo('#' + $this.attr('id') + '_input-group label:last-child div:last-child');
var $path = $('#' + $this.attr('id') + '_path', $parent).click(function(){
$this.click();
});
$this.bind('change.input_file_styler', function(){
$path.val(this.files[0] ? this.files[0].name : '');
});
});
});
})(Function('return this')());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<input type="file" id="file" data-label="Select file to upload:" data-button-label="...">