I want to preview and display the selected image on the jQuery image upload screen.

Asked 1 years ago, Updated 1 years ago, 38 views

There are two image input forms, Image 1 and Image 2, and I would like to preview the selected image, but if I select the image, the same image will be previewed on both Image 1 and Image 2.

What should I do to preview the selected image, image 1 (userfile1) and image 2 (userfile2), respectively?Could you tell me?

jQuery part

$(function(){
  $('input[type=file]').after('<span></span>');

  // Select a file to upload
  $('input[type=file]').change(function(){
    var file=$(this).prop('files')[0];

    // Stop processing except for images
    if(!file.type.match('image.*')){
      // clear
      $(this).val(');
      $('span').html(');
      return;
    }

    // image display
    var reader = new FileReader();
    reader.onload=function(){
      varimg_src=$('<img>').attr('src',reader.result);
      $('span').html(img_src);
    }
    reader.readAsDataURL(file);
  });
});

Form part

<form enctype="multipart/form-data" method="post">
<input type="file" name="userfile1" accept="image/*">
<input type="file" name="userfile2" accept="image/*">
</form>

jquery

2022-09-29 20:26

1 Answers

The problem is that the following code is used for all span elements.

$('span').html(img_src);


given the direction in which you don't really touch the code presented Wouldn't it be better to display only the span element next to the selected input element?

$(function(){
  $('input[type=file]').after('<span></span>');

  // Select a file to upload
  $('input[type=file]').change(function(e){
    var file=$(this).prop('files')[0];

    // Stop processing except for images
    if(!file.type.match('image.*')){
      // clear
      $(this).val(');
      $('span').html(');
      return;
    }

    // image display
    var reader = new FileReader();
    reader.onload=function(){
      varimg_src=$('<img>').attr('src',reader.result);
      $(e.target).next().html(img_src);
    }
    reader.readAsDataURL(file);
  });
});


2022-09-29 20:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.