views:

65

answers:

1

I have to be missing something simple, but I'm really not sure what. I'm not a JS veteran, so this may be an easy answer - sure hope so :).

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.

Any help/insight, as always, is appreciated!

+3  A: 

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.

Drew Wills
Thanks Drew :). Question: var locations inside the callback isn't executed right away, is it? I guess that is why I never thought to change that. I knew it was something simple though!
Dan