Global javascript variable not accessible in jquery change event

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-03-19T17:29:12Z Indexed on 2010/03/19 17:31 UTC
Read the original article Hit count: 251

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!

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript