user3789242
user3789242

Reputation: 103

calling function using javascript

In my HTML page I've the following ul:

 <ul id="inFile2"></ul>

and in my JavaScript page, I've this function

function handleFileSelect(event) {
 var files = event.target.files; // FileList object

 console.log(files);
 // files is a FileList of File objects. display first file name
 file = files[0];

 console.log(file);
 if (file) {

     readInputFile(file);
     console.log(file);

 }
}

I want to call the function in the ul. How could that happen? this is what I have tried so far

el=document.getElementById('inFile2');
el.on("change",handleFileSelect);

but gives me an error. What is the correct coding to call that function in the ul?

Upvotes: -1

Views: 111

Answers (3)

jirislav
jirislav

Reputation: 359

I can't see any reason of using jQuery .. I'd use pure JavaScript:

var el = document.getElementById("inFile2");
el.addEventListener("change", handleFileSelect, false);

jQuery is just another JS library which slows down script execution - not much, but does...

see Javascript Event Listening

Upvotes: 0

rink.attendant.6
rink.attendant.6

Reputation: 46287

Issues that I see with your code:

  1. el is a DOM object, not a jQuery object. If you do el instanceof $, you will get false.
  2. A change event does not fire on ul elements.
  3. There is no files property on an HTMLUListElement, if that's what el is representing.

HTML

<input type=file id=inFile2>

JavaScript

var $el = $('#inFile2');
$el.on('change', handleFileSelect);

// Alternatively
var el = document.getElementById('inFile2');
$(el).on('change', handleFileSelect);

With a file input (i.e. <input type=file>), there is a files property that returns a FileList. See HTMLInputElement for more details.

See jsFiddle for example.

Upvotes: 1

Sid M
Sid M

Reputation: 4364

Is this what you are looking for?

Fiddle: fiddle

$("#inFile2").click(function(){
   handleFileSelect('your_value')
});

function handleFileSelect(event) {
alert("called");
//your code here

}

Upvotes: 0

Related Questions