jqueryshow-hidecustom-data-attribute

show and hide elements based on data-* attribute


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

Solution

  • 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).