Search code examples
javascriptjquerydhtml

Can I run nest a $('element.class').each() function within the change() function for the same $('element.class')?


Specifically, I want to iterate over every element on the page, each time the value of one changes.

So to paraphrase my code I have:

$('select.filterbox').change(function() {
  // stuff
  $('select.filterbox').each(function() {
    // other stuff
  });
});

'stuff' all executes just fine, but 'other stuff' doesn't happen

Here's the full code

        // On Filterbox Change
    $j('select.filterbox').change(function() {

        // Show All Rows
        $j('#table1 tr').show();

        // For Each Filterbox
        $j('select.filterbox').each(function() {

            var selVal = $j(this).attr('value');
            var col = $j(this).closest('th').parent().children().index($j(this).closest('th'));
            alert('Column '+val+' : '+selVal);

            // If Selected Value Not Empty
            if(selVal != "") {

                // For Each Row
                $j('#table1 tr').each(function() {
                    var $tds = $j(this).find('td');
                    var cellVal = $tds.eq(col).text();
                    cellVal = $j.trim(cellVal);

                    // If td text != selected
                    if( cellVal != selVal ) {

                        // Hide this row
                        $j(this).hide();
                    }
                });
            }
        });
    });

Solution

  • Answer: yes you can. I've done a lot of stuff like that recently. Indeed, your code should do it. It is likely that you've made some small but significant error in your code that will need to be hunted down and fixed. I've done a lot of stuff stuff like that recently, too.

    More helpful answer: do things to figure out where the breakdown is. replace the "$('select.filterbox').each()" call with something obvious - say, calling .hide() on large chunks of your page. Make sure that line of code is even being called. If it is being called, put the "$('select.filterbox').each()" call back, then move the hide() call inside of it. If that works, then you know that it's running at least once. Change the hide() call to a (this).hide(), and see if you can see which one it's identified. Once you've narrowed down where it's failing you, it'll be a lot easier to figure out what you've done wrong.