Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass filename from file upload to text field

I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:

function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
        default:;
    } // switch
} // ff_uploadimages_action

ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.

like image 395
Fusionice Avatar asked Mar 30 '11 01:03

Fusionice


1 Answers

Here's one way to do it

document.getElementById('upload').onchange = uploadOnChange;

function uploadOnChange() {
  var filename = this.value;
  var lastIndex = filename.lastIndexOf("\\");
  if (lastIndex >= 0) {
    filename = filename.substring(lastIndex + 1);
  }
  document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />

you don't mention jQuery but given it's popularity here's the same solution using jQuery

jQuery:

$('#upload').change(function() {
    var filename = $(this).val();
    var lastIndex = filename.lastIndexOf("\\");
    if (lastIndex >= 0) {
        filename = filename.substring(lastIndex + 1);
    }
    $('#filename').val(filename);
});

Demo:

http://jsfiddle.net/pxfunc/WWNnV/4/

like image 88
MikeM Avatar answered Sep 20 '22 20:09

MikeM