Question

I have a form that needs to dynamically generate fields and those fields have various jquery functions called on them. Basically I am using slideUp and slideDown to show different options based on what the user selects. Consider the following code

    <div class="test">
    <div class="red" style="width:100px;height:100px;background-color:red; margin-bottom:10px;"></div>
    <div class="green" style="width:100px;height:100px;background-color:green;margin-bottom:10px;"></div>
</div>

<div class="test">
    <div class="red" style="width:100px;height:100px;background-color:red;margin-bottom:10px;"></div>
    <div class="green" style="width:100px;height:100px;background-color:green;margin-bottom:10px;"></div>
</div>

And the jquery

$('.green').hide();

        $('.red').click(function(){
            $('.green').show();
            });

Basically I want only the green box that is after the red one to show. While this example is simple and I could just duplicate my code and give the second item a different id, my real form is way more complex so what I would like to do is find a way to target items by classname within each "test" div.

Was it helpful?

Solution 2

Both answers are good, i'm just adding another option :

$('.red').click(function () {
    $(this).siblings('.green').show();
});

Jquery doc : http://api.jquery.com/siblings/

OTHER TIPS

what I would like to do is find a way to target items by classname within each "test" div.

Simple enough:

$('.red').click(function(){
    $(this).closest('.test').find('.green').show();
});

You can use next() method:

$('.red').click(function () {
    $(this).next('.green').show();
});

Change

$('.green').show();

to

$(this).parent('.test').children('.green').show();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top