简体   繁体   中英

JQuery Image Preview not working

I've seen several ways to display image preview but none of them seem to work or they work only in FF/Chrome.

Trying to keep it simple:

Markup:

<input type="file" id="logo-upload" onchange="changePreview();"/>
<br/>        
<img src='@Url.Image("logo.png")' alt="Preview" id="logo-preview"/>

Javascript:

<script type="text/javascript">

    function changePreview() {

        var input = $('#logo-upload').val();

         $('#logo-preview').attr('src', input)
                    .width(150)
                    .height(50);
         }

</script>

When debugging input shows the correct local image path but preview never shows up. Why and how can I get this to work (in all browsers ) ?

Thanks.

Try setting the $('#logo-upload').change(function(){}) instead of using onChange. I think that's a good start. Then put the jQuery inside $(document).ready(function(){}) . That could be another issue, if you're setting the script before the elements exist on the page.

If you can post more code, it would be beneficial.

Also, for IE, you're going to run into permissions issues that are on the user, which you don't have control over (at least in this situation). So, in those cases, you'll either have to upload the image first, to get the image from the server, OR they'll have to change their security settings to allow for this type of content to be accessed.

<input type="file" id="logo-upload" />
<br/>        
<img src="@Url.Image('logo.png')" alt="Preview" id="logo-preview"/>

<script type="text/javascript">
    $(document).ready(function() {
        $('#logo-upload').change(function() {
            var input = $(this).val();
            $('#logo-preview').attr('src', input).width(150).height(50);
        })
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM