Joe Pigott
Joe Pigott

Reputation: 8469

Getting the name of selected file using JavaScript

Here's the fiddle. I have a project where I am making non-styleable form elements,GitHub, and right now I am making a file input. You can find the source codes at the bottom of the question. I have used opacity: 0; on the input, and put a <span></span> over it. The extra space in the span is for the name of the file selected, but I am trying to think of a way to retrieve the file name using JavaScript or jQuery.

HTML:

<span>Choose File<input type='file'></span>

CSS:

body {
    background: #252525;
    color: #96f226
}
span {
    background: #4a4a4a;
    cursor: pointer;
}
input {
    opacity: 0;
    cursor: pointer;
}

JS/jQuery:

none yet

Upvotes: 1

Views: 3345

Answers (1)

guru1206
guru1206

Reputation: 68

Using jQuery, you can bind the onchange event of the file input to a function, and inside that function extract the name of the file.

Here is your html, with some id's for simple jquery access:

<span id="fileText"><input type='file' id="file">Choose File</span>

And some jQuery code:

$("#file").on("change", function()
{
    var value = this.value.split(/[\/\\]/).pop();
    $("#fileText").append(value);
});

Basically, this function will extract the filename from the input (this.value), then select the text after the last slash (directory).

The split() call uses a regexp to split the text into an array at either a forward slash or backward slash (i'm not sure if it is ever a forward slash, but just to be safe). If you just want to split it at the backward slashes, you don't have to use a regular expression, just call split("\"). the pop() returns the last item in the array.

Then, we append this new text to the end of the span.

Upvotes: 2

Related Questions