Question

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();
Was it helpful?

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

OTHER TIPS

If the data-show values are in your HTML or set as attributes on each object, you can do this entirely with a selector:

$('form > [data-show="pro"]').show();
$('form > [data-show="home"]').hide();

By way of explanation:

  • The form obviously selects form elements
  • The > selects a child of the form object
  • The [data-show="pro"] selects only the children that have an attribute named data-show that is set to the value of "pro"
  • The .show() calls the show method on those selected objects

If your data-show values are set with the .data() jquery method so the previous method would not work, then you may be better off setting state as a class name rather than a data value that you can more easily use in a selector. If these values were set as class names instead of data, the code would look like this:

$('form > .pro').show();
$('form > .home').hide();

Remember, you can have multiple class names on an object and object state that is directly used to control the presentation of the object (CSS styles, visibility, formatting, etc..) is much, much better to represent as class names rather than data-xxx attributes because it's much easier to use it in selectors for CSS or jQuery operations.

not quite sure what you're trying to do from code.

to access "data-" with JQ, i use:

$(elementSelector).attr('data-XXX');

where data-XXX is the attribute of the tag. This works in all browsers back to IE7 that i've seen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top