1

I want to add a function after I create an input element. but it didn't work. this is my code.

 <p id="pp">

    <input type="button" onclick="add();" value="Add Template"/><br>
    Photo: <input type="file" id="chooseFiles" name="photo[]"  class="inputFile"><br>

    </p>

    <script type="text/javascript">
    function add(){

        var text = document.createTextNode("Photo: ");

        var input = document.createElement("input");
        input.type="file";
        input.name="photo[]";
        input.class="inputFile";

    };


$(".inputFile").change(function (e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
    img.style.width='300';
    img.style.height='auto';

        var reader = new FileReader();
        reader.onloadend = function () {
            img.src = reader.result;
        }

        reader.readAsDataURL(file);
        $(this).after(img);
    }
});

</script>

the existing input works. but after createElement, function add() doesn't work..

Naveed
  • 2,942
  • 2
  • 25
  • 58

1 Answers1

1

You need to delegate the event handler to work with dynamically created elements, like

$(document).on("change",".inputFile",function (e) {})
T J
  • 42,762
  • 13
  • 83
  • 138