Reputation: 697
Hello im trying to get a variable from another function
Code:
$(document).ready(function() {
var totalFiles;
$(".filesUpload").on("change", function() {
var files = $(".filesUpload").prop("files");
var names = $.map(files, function(val) { return val.name; });
$("#uploadBar").modal('show');
var totalFiles = names.length;
});
$("#uploadBar").on("shown.bs.modal", function() { var test = totalFiles; alert(test); });
But right now i only get undefined on the totalFiles, but if i have a alert right after var totalFiles = names.length i get the right result, anyone knows what i can do and what am i doing wrong?
PS. I've checked other threads aswell and it still doesn't work.
Upvotes: 0
Views: 50
Reputation: 3217
You are declaring a local variable inside your callback. totalFiles = names.length;
is the right way to update the global variable.
var totalFiles;
$(".filesUpload").on("change", function() {
var files = $(".filesUpload").prop("files");
var names = $.map(files, function(val) { return val.name; });
$("#uploadBar").modal('show');
totalFiles = names.length;
});
Upvotes: 1
Reputation: 2443
Do not declare the variable twice. In your onChange
function, just use totalFiles
rather than declaring it again with the var
keyword.
$(".filesUpload").on("change", function() {
...
totalFiles = names.length;
...
});
Upvotes: 2
Reputation: 8858
Check your references to totalFiles
. You have one declared globally and then declared it locally in $(".filesUpload").on("change", function() {
.
This is what it needs to be :
$(document).ready(function() {
var totalFiles;
$(".filesUpload").on("change", function() {
var files = $(".filesUpload").prop("files");
var names = $.map(files, function(val) { return val.name; });
$("#uploadBar").modal('show');
totalFiles = names.length;
});
$("#uploadBar").on("shown.bs.modal", function() { var test = totalFiles; alert(test); });
Just remove 'var'
from the 1st function.
Upvotes: 2