I'm trying to display each image inside the custom style input file label before user uploads in the database. The script I'm using works at displaying only one image at the time and it is always located somewhere random. I'd like each image to appear as if they are inside the label. Each image does not display right inside the label. What am I doing wrong?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#photo1').attr('src', e.target.result);
}
reader.onload = function (e) {
$('#photo2').attr('src', e.target.result);
}
reader.onload = function (e) {
$('#photo3').attr('src', e.target.result);
}
reader.onload = function (e) {
$('#photo4').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".img1").change(function() {
readURL(this);
});
$(".img2").change(function() {
readURL(this);
});
$(".img3").change(function() {
readURL(this);
});
$(".img4").change(function() {
readURL(this);
});
.col-md-4 {
width: 33.33333333%;
display: inline-block;
margin-bottom: 15%;
}
.labelav.largeFile:after {
position: relative;
width: 5% !important;
max-width: 100%;
content: "Upload Photo + ";
text-align: center;
padding: 10%;
border-radius: 10px;
border: 5px dashed #ccc;
color: #ccc;
font-family: "Helvetica Neue", Helvetica, Arial;
font-size: medium;
}
.labelav.largeFile:hover:after {
background: #ccc;
color: #fff;
cursor: pointer;
}
.labelav.largeFile input.file {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div class='col-md-4'>
<label class="labelav largeFile" for="file">
<input type="file" id="file" class="file img1" name="photo1" />
<img id="photo1" src="#" alt="" />
</label>
</div>
<div class='col-md-4'>
<label class="labelav largeFile" for="file">
<input type="file" id="file" class="file img2" name="photo2" />
<img id="photo2" src="#" alt="" />
</label>
</div>
<div class='col-md-4'>
<label class="labelav largeFile" for="file">
<input type="file" id="file" class="file img3" name="photo3" />
<img id="photo3" src="#" alt="" />
</label>
</div>
<div class='col-md-4'>
<label class="labelav largeFile" for="file">
<input type="file" id="file" class="file img4" name="photo4" />
<img id="photo4" src="#" alt="" />
</label>
</div>
</form>