Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery loop through DIV's to hide /show

Tags:

jquery

I have a combo box with choice 0 - 8 and 8 sets of input fields where each set of input fields are wrapped around a div with the same class.

I need to find out how to use Jquery to hide/unhide the divs based on the selected combobox value. For example, if I select 2, then class="member1" and class="member2" needs to be visible, the rest are invisible. If i change my mind , and select 1, then class="member1" stay visible but member2 and the rest are set to invisible?

<div class="member1"> 
<input id="name1">
<input id="age1">
</div>
<div class="member2"> 
<input id="name2">
<input id="age2">
</div>
:
:
<div class="member8"> 
<input id="name8">
<input id="age8">
</div>
like image 311
Gotcha Avatar asked Feb 13 '26 00:02

Gotcha


1 Answers

It is rather simple. Considering selected_number is already an integer extracted from the select field you were talking about, the code could look like this:

jQuery(function(){
    var selected_number = 2;
    jQuery('.member1, .member2, .member3, .member4, .member5, .member6, .member7, .member8').hide();
    for (var i=1; i<=selected_number;i++){
        jQuery('.member'+i).show();
    }
});

As a proof see this jsfiddle (change selected_number value to see how it works).

like image 54
Tadeck Avatar answered Feb 20 '26 16:02

Tadeck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!