damon
damon

Reputation: 8467

execute a javascript function when user selects a file

In an html page ,I am adding an input element.

<input type="file" name="fileselect" id="fselect"> </input>

I wanted to execute a javascript function ,when a user selects a file.Suppose I want to write to the console too.

Is jquery select() the correct function to check if user has selected a file? I tried like this

$(document).ready(function(){
   $('#fselect').select(function(){ 
      console.log('selected');
      myfun(); 
    });
});

function myfun(){
   alert('you selected a file');
}

For some reason, when I select a file using the input element,nothing is written to console and no alert box appears..Is the select() call coded wrong?

Upvotes: 1

Views: 178

Answers (3)

Ram
Ram

Reputation: 144689

try this:

$(document).ready(function(){
   $('#fselect').change(function(){ 
      console.log('selected');
    });
});

Upvotes: 1

VisioN
VisioN

Reputation: 145398

You can use change event:

​$("#fselect").change(function() {
    // do something
});​​​​​​​

DEMO: http://jsfiddle.net/BtsHL/

Upvotes: 3

Quentin
Quentin

Reputation: 943510

The event you want is change, not select.

From the docs:

The select event is sent to an element when the user makes a text selection inside it.

And for change:

The change event is sent to an element when its value changes

Upvotes: 2

Related Questions