Variable scope problem in each method

Asked

Viewed 106 times

4

I’m having problems with assigning a variable within a 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 it was declared up there, an empty string. The assignment/concatenation on . each didn’t work... That seems to me to be a problem with scope. Would someone tell me what I’m doing wrong?

  • Your var Filters is catching something?

  • I believe there is no checkbox/radio with the class filter_check selected. Your code has no problem.

  • Filters has personal yes elements... More than 10 in total.

  • Could you post your HTML code so I can test it? I don’t understand why you’re accessing values within each with $(this). data('param').

2 answers

2

The $.each (or jQuery.each) which you are using is for arrays and objects. For collections of DOM elements, use .each right 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, the serialize:

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

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

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);

});

http://jsfiddle.net/vcqvjjhk/

try like this:

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

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.