egr103 egr103 -4 years ago 232
jQuery Question

Apply filename to label when uploading a file

I have hidden the file uploader input field. I use a label (so I can style it) as the clickable element to upload a file. Here's a jsFiddle

I've added a JS workaround to change the text of the label so when you select a file, the text "Upload a file" is replaced by the actual filename.

My problem is getting my code to work with multiple file uploaders. With the code below, no matter which file uploader I click on, the file name populates always the first file upload field only:


<p class="hide_this"><span class="wpcf7-form-control-wrap file-02"><input type="file" name="file-02" size="40" class="wpcf7-form-control wpcf7-file" id="file-01" aria-invalid="false"></span><label for="file-01"><span>Upload a file</span></label></p>

<p class="hide_this"><span class="wpcf7-form-control-wrap file-03"><input type="file" name="file-03" size="40" class="wpcf7-form-control wpcf7-file" id="file-02" aria-invalid="false"></span><label for="file-02"><span>Upload a file</span></label></p>

<p class="hide_this"><span class="wpcf7-form-control-wrap file-04"><input type="file" name="file-04" size="40" class="wpcf7-form-control wpcf7-file" id="file-03" aria-invalid="false"></span><label for="file-03"><span>Upload a file</span></label></p>


var filename = $(this).val().split('\\').pop();
var idname = $(this).attr('id');

Answer Source

The reason why this isn't working for you is that you have a mismatch of ids. You simply need to make the id of the <input> match the id of the related <span>.

Here is an updated fiddle:

Note: Don't forget to setup your fiddles to work with external libs

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