0

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.

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.