0

I want to implement in my yii2 app somethink like that: How to preview multiple images before upload? I need to show multiple images(max 5) Whats wrong with my code? When I choosed file nothing happened.

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<?php $form = ActiveForm::begin(); ?>


    <div class="row">
        <div class="col-lg-6">
            <p class="add_photo"><img class="describe_images" src="photo.png"></img>Добавить фото(до 5 штук)</p>
            <input id="file-input" type="file" multiple>
            <script>
            function previewImages() {
              var preview = document.querySelector('#preview');
              if (this.files) {
                [].forEach.call(this.files, readAndPreview);
              }
              function readAndPreview(file) {
                // Make sure `file.name` matches our extensions criteria
                if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
                  return alert(file.name + " is not an image");
                } // else...
                var reader = new FileReader();
                reader.addEventListener("load", function() {
                  var image = new Image();
                  image.height = 100;
                  image.title  = file.name;
                  image.src    = this.result;
                  preview.appendChild(image);
                }, false);
                reader.readAsDataURL(file);

              }
            }
            document.querySelector('#file-input').addEventListener("change", previewImages, false);
            </script>

        </div>

        <div class="col-lg-6 pixels-line">
            <div class="preview"></div>
        </div>
    </div>
    <div class="form-group">
        <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
    </div>

<?php ActiveForm::end(); ?>
Community
  • 1
  • 1
Rosti
  • 161
  • 1
  • 15

1 Answers1

0

Instead of .addEventListener("change", previewImages, false); try .addEventListener("click", previewImages, false);. As clicking on the UI button does nothing, the element would have to have a DOM change for the event listener to execute currently.

David J Eddy
  • 1,999
  • 1
  • 19
  • 37
  • I have that error always Uncaught TypeError: Cannot read property 'appendChild' of null at FileReader. (index.php:130) at line: preview.appendChild(image); – Rosti Feb 15 '17 at 14:52
  • 1
    That's because document.querySelector('#preview') is returning null. You have a div with class="preview", not id="preview", so the proper query is document.querySelector(".preview") – sonofagun Feb 15 '17 at 22:25