onchange file input change img src and change image color
Solution 1:
You need to send this
object only instead of this.value
while calling onchange
<input type='file' id="upload" onchange="readURL(this)" />
because you are using input
variable as this
in your function, like at line
var url = input.value;// reading value property of input element
Working DEMO
EDIT - Try using jQuery like below --
remove onchange from input field :
<input type='file' id="upload" >
Bind onchange
event to input field :
$(function(){
$('#upload').change(function(){
var input = this;
var url = $(this).val();
var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0]&& (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg"))
{
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else
{
$('#img').attr('src', '/assets/no_preview.png');
}
});
});
jQuery Demo
Solution 2:
Simple Solution. No Jquery
<img id="output" src="" width="100" height="100">
<input name="photo" type="file" accept="image/*" onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">
Solution 3:
in your HTML : <input type="file" id="yourFile">
don't forget to reference your js file or put the following script between <script></script>
in your script :
var fileToRead = document.getElementById("yourFile");
fileToRead.addEventListener("change", function(event) {
var files = fileToRead.files;
if (files.length) {
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
}
}, false);