Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

trigger file upload dialog using javascript/jquery

instead of using <input type="file">, is it possible to use <input type="text"> and then script it using javascript or jquery such that when the text box is clicked, the file upload dialogue shows up.....(and have it actually uploaded when it's submitted into a form)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You mean something like this?

http://jsfiddle.net/CSvjw/

$('input[type=text]').click(function() {
    $('input[type=file]').trigger('click');
});

$('input[type=file]').change(function() {
    $('input[type=text]').val($(this).val());
});

Note, though, that the value given by the file input is fake for security reasons. If you want to just have the file name show up, you can cut out the slashes.

Here's an example of how to do it using a string split and an array pop:

http://jsfiddle.net/CSvjw/1/

$('input[type=text]').click(function() {
    $('input[type=file]').trigger('click');
});

$('input[type=file]').change(function() {
    var vals = $(this).val(),
        val = vals.length ? vals.split('\').pop() : '';

    $('input[type=text]').val(val);
});

You can adjust this further to account for systems that use a forward slash as the directory separator. It's also important to note that if you do this, you'll lose the functionality of many modern browsers where users can drag files from their computer directly onto a file input. If I were you, I'd embrace that paradigm by styling the file input rather than trying to turn a text input into something that it is not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...