Repeating id's code will always get the first one you find. For this and others it is incorrect to repeat id's in HTML.
What you can do is to add the variable of the $imagem
loop to each id, thus creating distinct id's, just like in placeholder="Legenda da foto <?php echo $imagem ?>"
:
id="browsebutton<?php echo $imagem ?>"
id="my-file-selector<?php echo $imagem ?>"
id="label<?php echo $imagem ?>"
And in% with% of% with% also:
for="my-file-selector<?php echo $imagem ?>"
And jQuery will stay:
$(document).ready(function(){
$('[id^=browsebutton] :file').change(function(e){
var fileName = e.target.files[0].name;
$(this)
.closest(".input-group")
.find("[id^=label]")
.attr('placeholder',fileName);
});
});
The for
selector will pick up elements that have ids that start with label
, and o:
$(this)
.closest(".input-group")
.find("[id^=label]")
.attr('placeholder',fileName);
will change the placeholder of the element with the id beginning with [id^=browsebutton]
within the browsebutton
of the element.
Here's how it would look:
$(document).ready(function(){
$('[id^=browsebutton] :file').change(function(e){
var fileName = e.target.files[0].name;
$(this)
.closest(".input-group")
.find("[id^=label]")
.attr('placeholder',fileName);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="form-group">
<label for=""><i class="fas fa-caret-right"></i> Imagem 1:</label>
<div class="input-group">
<label id="browsebutton1" class="btn btn-primary input-group-addon" for="my-file-selector1" >
<input id="my-file-selector1" name="Arquivo[]" type="file" style="display:none;">
<i class="fas fa-upload"></i> Arquivo
</label>
<input id="label1" type="text" class="form-control" readonly="">
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="Legenda[]" placeholder="Legenda da foto 1" value="">
</div>
<div class="form-group">
<label for=""><i class="fas fa-caret-right"></i> Imagem 2:</label>
<div class="input-group">
<label id="browsebutton2" class="btn btn-primary input-group-addon" for="my-file-selector2" >
<input id="my-file-selector2" name="Arquivo[]" type="file" style="display:none;">
<i class="fas fa-upload"></i> Arquivo
</label>
<input id="label2" type="text" class="form-control" readonly="">
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="Legenda[]" placeholder="Legenda da foto 2" value="">
</div>
<div class="form-group">
<label for=""><i class="fas fa-caret-right"></i> Imagem 3:</label>
<div class="input-group">
<label id="browsebutton3" class="btn btn-primary input-group-addon" for="my-file-selector3" >
<input id="my-file-selector3" name="Arquivo[]" type="file" style="display:none;">
<i class="fas fa-upload"></i> Arquivo
</label>
<input id="label3" type="text" class="form-control" readonly="">
</div>
</div>