Search code examples
javascriptjqueryglobal-variablesscope

Global JavaScript variable not accessible in jQuery change event


I have to be missing something simple, but I'm really not sure what.

I have a button that, when clicked, gets JSON data. When a drop-down is changed, I check to see if there is data, if there is, I want to clear it out as the drop-down indicates what data to retrieve when the button is clicked

The Code:

 var selected, $locDialog;
 var locations = [];

$(function() {
// Save the selected Name
selected = $("#selected option:selected").val();

// Setup Dialog for Locations
$locDialog = $('#location-dialog').dialog({
    autoOpen: false
});

// If user changes the selected
// 1.  Prompt for confirmation
// 2.  If users confirms, clear  data
$('#selected').change(function() {
    if (locations) {
        var confirmed = confirm("Oh Rly?");
        if (confirmed) {
            // Clear data
            var locations;
        }
    }
});

// When user clicks "Location" Button..
$('.loc-select button').click(function() {
    if (!locations) {
        $.getJSON("/Controller/JSONAction", { selectedId: selected, pageNum: 1, pageSize: 100 }, function(data) {
            locations = data;
            $.each(locations, function(index, loc) {
                var $tr = $('<tr/>')
                    .append($('<td/>')
                        .append('<input type="checkbox" name="TEST-'+index+'" value="'+loc.Id+'"/>'))
                    .append('<td>' + loc.Name + '</td>');
                $("#location-dialog table tbody").append($tr);
            });
        });
    }
    $locDialog.dialog('open');
    return false;
});
});

Here's the thing, Inside the .click(...) callback, I can see locations is []. Now, when I am in the .change(...) callback, I see locations is undefined.


Solution

  • Try changing this line...

    // Clear data
    var locations;
    

    to this...

    // Clear data
    locations = [];
    

    Here's what's happening: you're declaring a new 'locations' variable which is covering the global one. In JavaScript, any variables declared in the function are visible throughout the function -- even if they're declared in (what looks to you like) a nested scope.