Cthulhu Cthulhu - 1 year ago 75
Javascript Question

Change label text for multiple inputs

I have a dynamic page that can have a lot of

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">

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

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

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


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

Answer Source

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

$('input:file').change(function() {

Working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download