For the first input it works well, but not for the second. Instead of updating the second one it updates the first. How do I separate this two input previews with the same function?
JavaScript
x
11
11
1
function readURL(input) {
2
if (input.files && input.files[0]) {
3
var reader = new FileReader();
4
5
reader.onload = function(e) {
6
$('#blah').attr('src', e.target.result);
7
}
8
9
reader.readAsDataURL(input.files[0]); // convert to base64 string
10
}
11
}
JavaScript
1
6
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<input type="file" onchange="readURL(this);" required>
3
<img id="load" src="../img/preview.png" alt="loading" width=50 height=50>
4
5
<input type="file" onchange="readURL(this);" required>
6
<img id="load" src="../img/preview.png" alt="loading" width=50 height=50>
Advertisement
Answer
Firstly, the IDs should be unieque, so set “load” to “load1” and “load2” for the img element.
And you should distinguish the output target by the input.
$('#blah').attr('src', e.target.result);
always updates the element ‘#blah’.
Therefore, add an argument to the readURL() that specifies the output destination, and modify it to update there.
JavaScript
1
12
12
1
function readURL(input, target) {
2
if (input.files && input.files[0]) {
3
var reader = new FileReader();
4
5
reader.onload = function(e) {
6
$(target).attr('src', e.target.result);
7
}
8
9
reader.readAsDataURL(input.files[0]); // convert to base64 string
10
}
11
}
12
JavaScript
1
6
1
<input type="file" onchange="readURL(this, '#load1');" required>
2
<img id="load1" src="../img/preview.png" alt="loading" width=50 height=50>
3
4
<input type="file" onchange="readURL(this, '#load2');" required>
5
<img id="load2" src="../img/preview.png" alt="loading" width=50 height=50>
6