Cthulhu Cthulhu - 7 months ago 13
Javascript Question

Change label text for multiple inputs

I have a dynamic page that can have a lot of

input[type="file"]
fields. I need to change the label of every input once a file is selected.

So, for each input, if:


  • Empty: text = "upload";

  • File selected: text = name of file.



Here is a sample of HTML:

<label for="upload-qm1">
<span class="button">upload</span>
<input id="upload-qm1" type="file" accept=".pdf, .doc">
</label>


I know how to do this for a single
input
, using this code:

$('label[for="upload-qm1"] span').text($(this).val());


However, I don't know how many
input
fields I will have on my page. I tried something like this:

$(this).parent('label').find('span').text($(this).val());


but unfortunately it doesn't work. Any help on how I can get a method for changing all
input
fields?

Answer

You can use DOM traversal to find the span related to the input which was changed. Try this:

$('input:file').change(function() {
    $(this).prev('span').text($(this).val());
})

Working example

Comments