Skip to content Skip to sidebar Skip to footer

JavaScript : Onchange Function Causes Error/ Didn't Work

The Following code will add File upload and preview field. This single img works but not in js
your imageCopy

Other way to do:

upload.addEventListener('change', function () {
    document.getElementById(img.id).src = 
    window.URL.createObjectURL(this.files[0])
})

Solution 2:

Problem Solved

Working Fine.

All image fields can able to preform upload and preview function of 'n' fields.

<b>This single img works but not in js</b> <br>
<img id="img" alt="your image" width="100" height="100" />
<input type="file" onchange="document.getElementById('img').src = window.URL.createObjectURL(this.files[0])">

<br/>
No of Img <input type="text" id="noi" name="noi" value="" onkeyup="addFields()">
    <br />
<script>
            function addFields(){
            // Number of inputs to create
            var number = document.getElementById("noi").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            var array = ["CRICTICAL","HIGH","LOW","INFO"];
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=1;i<=number;i++){
                var img = document.createElement("img");
                img.width="100";
                img.height="100";
                img.id="img "+i;

                var upload = document.createElement("input");
                upload.type="file";
                upload.id="upload "+i;
//Working_______________
                upload.onchange=upload.onchange= function () {

                    var img_id=this.getAttribute('id');
                    var imgId = img_id.charAt(7) ; 
                     document.getElementById("img "+imgId).src = window.URL.createObjectURL(this.files[0])
                      }

//________________________________________
                container.appendChild(img);
                container.appendChild(upload);
                container.appendChild(document.createElement("br"));
            }
        }
</script>
    <div id="container"/>

Post a Comment for "JavaScript : Onchange Function Causes Error/ Didn't Work"