d'art
d'art

Reputation: 87

How to fire cancel on open dialog file input on jquery

Hi all i have code for multiple upload image, but i want only one image per upload. so I create the input file every time I clicked the upload button with the dynamic id. however I have problems checking whether the user chooses the file to upload or press the cancel button. because if the user pressed the cancel button I want to delete the input file I have created. for full sourcenya as below:

$(document).ready(function () {
    $("#btnimg").click(function () {
        //check input file id number
        var counter = $("input[id^='upload']").length;
        //add input file every btnimg clicked
        var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
        $("#result").append(html);
        //trigger to dialog open file
        var upload = $('#upload_' + counter);
        upload.trigger('click');
        upload.on('change', function () {
            console.log('change fire...');
            var inputFiles = this.files;
            var inputFile = inputFiles[0];
            var reader = new FileReader();
            reader.onload = function (evt) {
                var imghtml = "<img id='img_upload_" + counter + "' src='" + evt.target.result + "' width='50px;' height='50px;'/>";
                $('#previewimage').append(imghtml);
            };
            reader.onerror = function (event) {
                alert("something: " + event.target.error.code);
            };
            reader.readAsDataURL(inputFile);
        });
        //if file not selected or user press button cancel on open dialog
        //upload.remove();
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
    <div id="result"></div>
    <button id="btnimg">upload image</button>
    <div id="previewimage">
    </div>
</body>

thank you in advance,

Upvotes: 0

Views: 969

Answers (2)

Kaiido
Kaiido

Reputation: 137141

That all sounds like an xy-problem to me.

I have not (yet) got a response from you about the why you want to do it, so I will base my answer on two probable situations:

If you want to keep track of the selected Files, in order to be able to do anything with them later (e.g send them through AJAX), then use a single <input>.
At every change event, you will store the new File in an Array, from where you will also be able to do something with later on:

(function() {
  // this Array will hold our files, should be accessible to the final function 'doSomething'
  var savedFiles = [];
  var counter = 0;
  var upload = $('#upload');
  upload.on('change', onuploadchange);

  $("#btnimg").click(function routeClick() {
    upload.trigger('click');
  });

  $('#endbtn').click(function doSomething() {
    console.log(savedFiles);
  });

  function onuploadchange() {
    var inputFiles = this.files;
    var inputFile = inputFiles[0];   
    if (!inputFile) { return; } // no File ? return
    savedFiles.push(inputFile); // save this File
    // don't use a FileReader here, useless and counter-productive
    var url = URL.createObjectURL(inputFile);
    var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
    $('#previewimage').append(imghtml);
    $('#endbtn').removeAttr('disabled');
  }
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
  <!-- A single input to save them all-->
  <input type='file' id='upload' style='display:none;' />
</div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>
<button id="endbtn" disabled>do something with saved files</button>

If, for an obscure reason, you absolutely need to keep all the filled <input> elements in your document, then create a new one only if the last one is itself filled.

$(document).ready(function() {
  $("#btnimg").click(function() {
    // grab previous ones
    var inputs = $("input[id^='upload']");
    // get the last one we created
    var last = inputs.last();
    var counter = inputs.length;
    console.log(counter);
    var upload;
    // if there is no input at all, or if the last one is already filled with a File
    if (!last.length || last[0].files.length) {
      console.log('create new input');
      upload = makeNewInput();
    } else {
      // use the last one
      upload = last;
    }
    //trigger to dialog open file
    upload.trigger('click');

    function makeNewInput(counter)  {
      var html = "<input type='file' id='upload_" + counter + "' style='display:none;'/>";
      var el = $(html);
      el.on('change', onuploadchange);
      $('#result').append(el);
      return el;
    }

    function onuploadchange() {
      var inputFiles = this.files;
      var inputFile = inputFiles[0];
      var url = URL.createObjectURL(inputFile);
      var imghtml = "<img id='img_upload_" + counter + "' src='" + url + "' width='50px;' height='50px;'/>";
      $('#previewimage').append(imghtml);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="result"></div>
<button id="btnimg">upload image</button>
<div id="previewimage">
</div>

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can check the .length of <input type="file"> element .files property to determine if a file is selected by user

Upvotes: 1

Related Questions