samuel toh
samuel toh

Reputation: 7076

How can I get variable from another function?

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?

Upvotes: 1

Views: 82

Answers (2)

Ilario Pierbattista
Ilario Pierbattista

Reputation: 3265

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>

Upvotes: 1

alalalala
alalalala

Reputation: 889

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);
});

Upvotes: 3

Related Questions