show and hide elements based on data-* attribute

Chris Sobolewski picture Chris Sobolewski · Jan 27, 2012 · Viewed 29.1k times · Source

This seems like it should be trivial for JQuery to do, but this function is hiding the whole form... can someone point me in the right direction?

$('form')
        .children()
        .filter(function(){
            return $(this).data('show', 'pro')
        })
        .show();
$('form')
         .children()
         .filter(function(){
             return $(this).data('show', 'home')
         })
         .hide();

Answer

Joseph Silber picture Joseph Silber · Jan 27, 2012

You're passing 2 arguments to the data method, thereby setting it instead of retrieving the old value.

Use this instead:

$('form')
        .children()
        .filter(function(){
            return $(this).data('show') === 'pro';
        })
        .show();
$('form')
         .children()
         .filter(function(){
             return $(this).data('show') === 'home';
         })
         .hide();

You could also cache your selector for performance (or use end).