user2625363
user2625363

Reputation: 915

How to trigger jquery input file?

I am trying to trigger input tag to select a file by a button click though jquery. code example like the following

<input type="file" id="input_file"/>

<button onclick="select_file()"/>

function select_file() {
${'input_file').select("http://www.someimage.com/image.gif");
}

After hours of research, I still have not got the solution how I could make this happen.

Appreciate for any suggestion or solution

Thanks you

Upvotes: 2

Views: 9899

Answers (4)

bcarn
bcarn

Reputation: 133

You should use

<input type="hidden" id="input_file"/>
<button onclick="select_file()"/>

function select_file() {
 $('input_file').val("http://www.someimage.com/image.gif");
}

The input type of file is used mainly for local file system files.

EDIT: Sorry about the typos

Upvotes: 0

alexdmejias
alexdmejias

Reputation: 1419

There were a couple of things wrong with your snippet. You were not using script tags, you had forgotten the '#' before ID selectors and you had a curly bracket after the dollar sign.

<input type="file" id="input_file/>

<button onclick="select_file()"/>
<script>    
function select_file() {
    $('#input_file').select("http://www.someimage.com/image.gif");
}
</script>

Although the way you are approaching your problem technically works, I would never recommend it since it can lead to unmaintainable code. A better approach would be something like:

<input type="file" id="input_file/>

<button class="changeInputButton" />
<script>    
$('.changeInputButton').on('click', function () {
  $('#input_file').val("http://www.someimage.com/image.gif");
});
</script>

Upvotes: 0

ChaoticNadirs
ChaoticNadirs

Reputation: 2290

I was going to suggest:

$("#input-file").trigger("click");

but then I remembered there are security restrictions which prevent triggering and setting the values of file input dialogs.

There are some ways around it though, take a look at this question: https://stackoverflow.com/a/3030174/992435

Upvotes: 1

BlackPearl
BlackPearl

Reputation: 2775

You have typos in your codes... correct as follows;

<input type="file" id="input_file"/>

<button onclick="select_file()"/>

function select_file() {

   $('#input_file').val("http://www.someimage.com/image.gif");

}
  1. Use Val in place of Select
  2. You missed a # sign in the function
  3. You missed a quote in the file input tag
  4. You used a curly brace instead of a bracket

Upvotes: 0

Related Questions