Reputation: 103
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
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
Reputation: 46287
Issues that I see with your code:
el
is a DOM object, not a jQuery object. If you do el instanceof $
, you will get false
.change
event does not fire on ul
elements.files
property on an HTMLUListElement
, if that's what el
is representing.<input type=file id=inFile2>
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