1

My case like this :

Html code (This is modal) :

<div class="modal-body">
    ...
    <input type="file" id="change-image" name="replace">
    ...     
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>    
</div>

If I click input type file, it will run the javascript code :

$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});

There exist variable data image

If I run this :

$('#confirm-edit-image').on("click",function(){
    // get variable data
});

I want to get the variable data image

How can I do it?

samuel toh
  • 6,836
  • 21
  • 71
  • 108
  • 2
    Are those functions in the same file? The faster approach is to globally declare `data` and the use it in your jquery callbacks – Ilario Pierbattista Jun 08 '17 at 08:38
  • In the code shown, `data` is not a local variable so it's already accessible beyond the `change` handler, though obviously you do need to test its value in case it isn't set yet (if the user clicks the button before the file input). – nnnnnn Jun 08 '17 at 08:39

2 Answers2

3

Make sure that “data” is a global variable

var data;

$('#change-image').change(function (e) {
    data = new FormData();
    data.append('file', $('#change-image')[0].files[0]);
});

$('#confirm-edit-image').on("click",function(){
    console.log(data);
});
1

Declaring data outside those functions is enough to share the variable itself. Here's a live snippet.

For further details about variable scope in javascript, you can refer to this answer What is the scope of variables in JavaScript?.

var data = new FormData();

$('#change-image').change(function (e) {
    data.append('file', $('#change-image')[0].files[0]);
});

$('#confirm-edit-image').on("click",function(){
    var empty = true;
    for (entry of data.entries()) {
      console.log(entry);
      empty = false;
    }
    if(empty) { console.log("Please add a file first!\n"); }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-body">
    ...
    <input type="file" id="change-image" name="replace">
    ...     
    <button type="button" class="btn btn-success" id="confirm-edit-image">
        Save
    </button>    
</div>
Ilario Pierbattista
  • 3,175
  • 2
  • 31
  • 41