3

I am trying to show image on upload, but script is not working.. not getting what's wrong, help me if you get it

<apex:page controller="tryPicUpload" >

<apex:includeScript value="http://code.jquery.com/jquery-1.8.2.js"/> 
<script>
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        readURL(this);
    });
 </script>   

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>
</apex:page>
3

If you use your browser dev tools and inspect your script you will find out why your current script is not working..

I just used your code in my dev org and went thru the dev tools and identified & fixed the below issues.

  1. The jQuery Script itself is not loaded since you have used http instead of https
  2. once you change that and jquery loads, its better to use the noConflict option as suggested in this article
  3. then your event binding of the image node needs to happen inside the document ready handler so that the binding happens properly

here's the updated code which works now

<apex:page controller="hello" >

<apex:includeScript value="https://code.jquery.com/jquery-1.8.2.js"/> 
<script>
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $j = jQuery.noConflict();

    $j(document).ready(function(){ 
       $j("#imgInp").change(function(){
         readURL(this);
       });
    });
 </script>   

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>
</apex:page>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.