Pass variable outside of function. JQuery

17,163

Solution 1

This happens because of JS variable scope. More info for ex. What is the scope of variables in JavaScript?

In general a variable cannot be used outside the scope in which it's defined.

That's why this should work.

    var checkBoxClasses = [];

    $(currentMap).find(':checkbox').filter(':checked').each(function () {
        var b = $(this).attr('class').split(' ');
        checkBoxClasses.push(b[0]);
    });

    alert(checkBoxClasses);

In your version the anonymous function inside each-loop means variables defined inside that function are not visible outside that function.

Solution 2

You could use an array to which append the results:

var classes = new Array();
$(currentMap).find(':checkbox').filter(':checked').each(function () {
    var b = $(this).attr('class').split(' ');
    classes.push(b[0]);
});
alert(classes);

Another possibility is to use the .map function which seems more adapted to your requirements:

var classes = $(currentMap).find(':checkbox:checked').map(function () {
    return $(this).attr('class').split(' ')[0];
}).toArray();
alert(classes);

Solution 3

You would have to declare the variable outside the function scope, otherwise the variable will be private to the anonymous function.

var checkBoxClasses;
$(currentMap).find(':checkbox').filter(':checked').each(function () {
   var b = $(this).attr('class').split(' ');
   checkBoxClasses = b[0];
});

alert(checkBoxClasses);

However, as you are looping over the checkboxes, only the last checkbox will be alert, if you do it this way. If you like to do an alert for every checkbox, you would have to move the alert into the loop as well. Or, if you would like to alert all the checkboxes in a single alert, you could use either an array, or extend the string with each new checkbox, instead of replacing it entirely.

Solution 4

Why not :

var checkBoxClasses; // "global" variable, outside function

    $(currentMap).find(':checkbox').filter(':checked').each(function () {
                var b = $(this).attr('class').split(' ');
                checkBoxClasses = b[0];

            });

   alert(checkBoxClasses);
Share:
17,163
Cecil Theodore
Author by

Cecil Theodore

Updated on June 13, 2022

Comments

  • Cecil Theodore
    Cecil Theodore almost 2 years

    I am trying to pass the variable checkBoxClasses outside of the current function.

    How can I do this?

    $(currentMap).find(':checkbox').filter(':checked').each(function () {
                var b = $(this).attr('class').split(' ');
                var checkBoxClasses = b[0];
    
            });
    
            alert(checkBoxClasses);
    
  • Darin Dimitrov
    Darin Dimitrov over 12 years
    This way you will get the class only of the last checkbox.