Liaoo
Liaoo

Reputation: 425

javascript global variable becomes empty after being used

I have a global variable that is assigned a value on page load via document.ready(), but when I access it from an event method, it becomes empty.

So to check whether or not the variable is assigned a value, I added an alert(variable.length) right after assignment which shows the expected value, but when I do the same in the event triggered method, the value is always 0

This is what I've done

document.ready()

    var selectedCategory = new Array();
    $(document).ready(function () {
        selectedCategory = $("#<%=hfdGenreList.ClientID%>").val().split(',');
        alert(selectedCategory.length);
    });

strong text

    function moveToTextbox() {
        alert(selectedCategory.length);
      // some code
    }

Upvotes: 1

Views: 2116

Answers (1)

Remove the "var" syntax to create a global var, or be explicit about creating a global var hanging from window objetc, so:

Alternative 1 (removing 'var'):

selectedCategory = new Array();
$(document).ready(function () {
    selectedCategory = $("#<%=hfdGenreList.ClientID%>").val().split(',');
    alert(selectedCategory.length);
});

Alternative 2 (explicit global var from window object):

var window.selectedCategory = new Array();
$(document).ready(function () {
    selectedCategory = $("#<%=hfdGenreList.ClientID%>").val().split(',');
    alert(selectedCategory.length);
});

function moveToTextbox() {
        alert(window.selectedCategory.length);
      // some code
    }

Upvotes: 2

Related Questions