Problem with variable scope in each method

4

I'm having problems with assigning to a variable within an each in jQuery.

(function(){
    var filters = $(".filter_check:checked");
    var hiddenFields = '';

    $.each(filters, function(){
        hiddenFields += "&" + $(this).data('param') + "=1";
    });

    console.log( hiddenFields );
})();

On the last line, when I check the output, I see that the variable is exactly as declared above, an empty string. The assignment / concatenation in .each did not work ... This seems to me to be a problem with scope. Could anyone tell me what I'm doing wrong?

    
asked by anonymous 11.03.2015 / 15:09

2 answers

2

The $.each (or jQuery.each ) that you are using is for arrays and objects. For collections of DOM elements, use .each directly in the collection:

var filters = $(".filter_check:checked");
var hiddenFields = '';

filters.each(function(){
    hiddenFields += "&" + $(this).data('param') + "=1";
});

console.log( hiddenFields );

But there's an easier way to do what you want, serialize :

var filters = $(".filter_check:checked");
console.log( filters.serialize() );

This will work as your code, as long as the checkboxes in question have the name attribute with value equal to their data-param , and have value with value 1 .

    
11.04.2015 / 18:43
0

I believe your $ .each code is wrong. I just ran a test and it worked:

$(function(){
    var response = "";
    var items = ['a','b','c'];

    $.each(items,  function(index, item){

        response += item;

    });

    console.log(response);

});

link

try this:

(function(){
    var filters = $(".filter_check:checked");
    var hiddenFields = '';

    $.each(filters, function(i, filter){
        hiddenFields += "&" + filter.data('param') + "=1";
    });

    console.log( hiddenFields );
})();
    
11.03.2015 / 18:23