burgerB
burgerB

Reputation: 772

jQuery: dynamically selecting elements by class with .find()

I am working on a form with many sections. Within each section there is a radio button used to indicate which units the user would like to use (lbs/oz vs kg, etc). When they click on a unit, I'd like to hide() all the inputs in the same section, then show() the relevant ones.

I can't get it to work. I think I am misunderstanding the find() function somehow because it is not selecting any elements.

var show_hide_units = function (selectedUnitElement) {
    $element = $(selectedUnitElement);
    unit_class = $element.attr("class");
    $section = $($element.parents('.measurement'));
    $inputs = $($section.find('.inputs *'));
    $inputs.hide();
    $inputs.find('.' + unit_class).show();
};

Here is a fiddle showing more context: http://jsfiddle.net/32Q9t/

Any pointers would be much appreciated.

Upvotes: 1

Views: 3519

Answers (3)

Denys Séguret
Denys Séguret

Reputation: 382464

If you choose to hide all '.inputs *' elements (which isn't the simplest solution at all), then you must show much more inputs that what you do, as elements "visible" in hidden aren't really visible :

$inputs.parent().find('.' + unit_class+', .' + unit_class+' *').show();

Demonstration

A simpler solution would be to hide/show only one level of elements :

$('.inputs > *').hide();
$('.inputs > .'+unit_class).show();

Demonstration

Upvotes: 0

ngasull
ngasull

Reputation: 4216

http://api.jquery.com/find/ :

.find( selector ) Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

So just use $('.youClass') to match target elements.

var show_hide_units = function (selectedUnitElement) {
    var targetClass = $(selectedUnitElement).attr('class');
    $('.inputs > *').hide();
    $('.' + targetClass).show();
};

There you go with your forked fiddle: http://jsfiddle.net/BE8ZV/

Upvotes: 1

Michael Geary
Michael Geary

Reputation: 28880

Do you know how to use the JavaScript debugger? That's the real answer to your question. Here's how to get started: In your fiddle, insert a debugger; statement at the beginning of your show_hide_units() function, like in this updated fiddle. I also made a few minor changes to your code, adding missing var declarations, and removing the redundant $() wrappers on two lines. (The return value from .parents() or .find() is a jQuery object already.)

What I didn't do is fix the bug. Now here is how to start: load that page in Chrome and open the Developer Tools. Then click one of your radio buttons and it will stop on that debugger; statement. From there you can examine variables by hovering over them, single-step through the code, and do all sorts of useful things. Poke around in there for a while and you should find the bug, or if not, report back with what you've discovered in the debugger and we can kick it around some more.

Upvotes: 0

Related Questions