-1

Please attention that the included range of $(document).ready(function(){})

the original code is:

    var files = [];
    $(document).ready(function(){
      $("input").change(function(){
        files = this.files;
      });
    });

    $("#upload-btn").click(function(){
      var fd = new FormData();
      for (var i = 0; i < files.length; i++) {
        fd.append("file", files[i]);
      }
      $.ajax({
        url: "/upload/",
        method: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success: function(data){
          console.log(data);
        }
      });
    });

the changed code is:

var files = [];
$(document).ready(function(){
    $("input").change(function(){
        files = this.files;
    });

    $("#upload-btn").click(function(){
      var fd = new FormData();
      for (var i = 0; i < files.length; i++) {
        fd.append("file", files[i]);
      }
      $.ajax({
        url: "/upload/",
        method: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success: function(data){
          console.log(data);
        }
      });
    });
});

the point is the included range of $(document).ready(function(){}) I don't know what's the different

zjien
  • 1
  • 3
  • 1
    The answer depends on where this script is located, and how and when those elements are placed in the DOM. – James Thorpe Oct 05 '15 at 10:06
  • What do you mean with "doesnt put into"? Could you clarify please. – realappie Oct 05 '15 at 10:06
  • 1
    What's the actual question? I'm assuming you're wondering why the upload button click event has been put out of the document ready? Very simple, you can't click a button before the document has been loaded. I.E. you don't have to wait for the document.ready – Steyn Oct 05 '15 at 10:06
  • You CAN click before document ready. Programatically. So it should be in document.ready – FLX Oct 05 '15 at 10:10

1 Answers1

0

You are right in your though about why one event binding is in the ready event handler and the other one isn't.

Normally the script is in the head of the page, and both event bindings need to be in the ready event handler to work. You need to run the event binding code when you know that the element already exists.

If you include the code in the page after the elements, then you don't need the ready event to know that the elements exist.

There is one case where the original code would make sense. That would be if it was included below the button but above the input. Then you know that the button already exists, but you need the ready event to wait for the input to exist.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005