简体   繁体   中英

SELECT image from preview before upload

I'm trying to make a javascript function to let people select a primary image after selected their images and right before the upload. I'm using an image-uploader JS lbirary from Christian Bayer. It gives several options, for example I can preview the images, I can delete them etc. Bt it also means that I only have this in my html part:

<div class="input-images" name="thumbnailimage"></div>

So I can't really use onclick event or anything here. I'm trying to select the images by adding each preview image an onclick event and I want to put it's path into a hidden input, so I can upload it to a different table. This is how my div looks like after adding images:

<div class="uploaded">
<div class="uploaded-image" data-index="0" id="image-0">
<img src="blob:http://localhost/11388451-d0be-454c-aabe-20a77e8c8835">
<button class="delete-image"><i class="iui-close"></i></button>
</div>
<div class="uploaded-image" data-index="1" id="image-1">
<img src="blob:http://localhost/5920bf98-8b23-4bb2-b573-20fe94620437">
<button class="delete-image"><i class="iui-close"></i></button>
</div>
</div>

I'm trying to get the images this way:

$('#image-upload').change(function() {
  if ($(this).val().length) {
  var foo = document.getElementsByClassName('uploaded-image');
  console.log(foo);
  } else {
    foo = "";
    }
});

But how can I add onclick event to each image to select them and be able to copy it to a hidden input?

Please review the following example:

https://jsfiddle.net/Twisty/mbvqoyn4/14/

JavaScript

$(function() {
  var selected = [];
  $('.input-images-1').imageUploader();

  $(".uploaded").on("dblclick", "img", function() {
    console.log("Double Click on Image", $(this).attr("src"));
    selected.push({
      id: $(this).parent().data("index"),
      src: $(this).attr("src")
    });
    $(this).parent().addClass("selected-image");
    console.log(selected);
  });
});

I moved the event to a Double Click as there is already a Click event assigned to the parent of the Image that is bubbling up:

function(e) {
  d(e)
}

But you can see how you can bind an event to the dynamically created object using the .on() method. I then store these in an array and you can then send this data to a hidden field or use AJAX to send it to your server in the background.

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