1

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
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.