2

I have the following html setup and cannot solve this issue.

When a button in the html document gets clicked, an element

<div id='wrapper'>
   <input id='fileUpload' name='fileUpload' type='file' onchange='uploadpreview(this.id)' multiple />
    <br />
    <div id='image-holder'></div>
   </div>

gets added using the function

function add(){
$j("<?php echo($divoutput)?>").insertBefore("#addbox");
}

(the php code has the html format in there).

However when this is done, the javascript function (Which is already in the html document and does not get added via a code) does not work:

$("#fileUpload").on('change', uploadpreview() {


     //Get count of selected files
  var countFiles = upload[0].files.length;

     var imgPath = upload[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL(upload[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 }

It throws an error that length cannot be read etc, even though a file has been uploaded.

What can be the trouble of this?

I have tried the code separately (without being added via a code) and everything works flawlessly.

Please help!

Tom
  • 848
  • 1
  • 5
  • 24
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Josh Beam Oct 27 '15 at 01:45
  • Do you add php code via jquery? I ain't no expert but that seems to not work. and never did. and probably never will. try using ajax. That way you also have a way to bind events to it. – Le 'nton Oct 27 '15 at 01:47

1 Answers1

0

Ok so let see if i understand you are adding stuff to the dom and wish to bind events to the newly added elements. if thats the case bind the events with the body so it "scans" from body down like this

$('body').on( 'change', '#fileUpload', function() {
    DoSomething();
});

hope ite helps

jstuartmilne
  • 3,838
  • 1
  • 15
  • 22