1

I'm trying to code a custom upload button. I've hidden the regular one and then put a div with image background over the top.

It works great but I want to fill the (disabled) input field below with the file name once the user selects a file but it's not working.

JavaScript:

document.getElementById("upload_button").onchange = function () {
document.getElementById("upload_file").value = this.value;
};

HTML:

<div id="Form_FileInput_Container"><input type="file" id="upload_button" /></div>
<input class="Form_Input" id="upload_file" placeholder="Choose File" disabled="disabled" />

CSS:

#Form_FileInput_Container { position: relative; width: 100px; height: 100px; background: #e5e5e5 url('path/to/upload/image/forms_upload.png') no-repeat; border: 1px solid #cccccc; }
#Form_FileInput_Container input { filter: alpha(opacity=0); opacity: 0; width: 100px; height: 100px; }

Any help is most appreciated :)

1
  • Tried to reproduce with your code here (fiddle) but it works, so I'm guessing you're executing JavaScript at the wrong time Commented Apr 12, 2014 at 11:44

2 Answers 2

4

Make sure you attach your JavaScript after the elements exist.

<input id="foo" type="file" />
<input id="bar" type="text" placeholder="Choose File" disabled />
// after elements exist
var foo = document.getElementById('foo'),
    bar = document.getElementById('bar');

foo.addEventListener('change', function () {
    var slash = this.value.lastIndexOf('\\');
    bar.value = this.value.slice(slash + 1);
});

DEMO

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

1 Comment

Yeah this worked. I had the JavaScript before the elements, so maybe that was the issue. This works great though, thanks Paul S!
0

HTML:

<input type="file" id="upload_button" onchange="cutomButton()" /> 

JS:

function customButton() {
    var z=document.getElementById("upload_button").value;
    document.getElementById("upload_file").value = z;
    alert(document.getElementById("upload_file").value);
}

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.