Reputation: 1793
I am trying to show elements by the select option value of each div.wrap
.
Here is a jsfiddle https://jsfiddle.net/na9rbdyo/1/
<div class="wrap">
<select id="type">
<option default value="0">-- Select One --</option>
<option value="1">Hot</option>
<option value="2">Cold</option>
</select>
<div class="hot">
This is hot!
</div>
<div class="cold">
This is cold!
</div>
</div>
Basically there will be multiple divs with the same structure. The user can use the select box to select an option(hot and cold for demo purposes) if the users selected cold then only the div .cold
will show.
Each select option should only effect the .wrap
div that is in. Any help would be greatly appreciated.
Upvotes: 2
Views: 77
Reputation: 17638
With some modifications I've got it working
First never have more than one element with the same id this will cause problems
so I changed them to classes
I also add a little be of css
HTML
<div class="wrap">
<select class="type">
<option default value="0">-- Select One --</option>
<option value="1">Hot</option>
<option value="2">Cold</option>
</select>
<div class="hot">
This is hot!
</div>
<div class="cold">
This is cold!
</div>
</div>
<div class="wrap">
<select class="type">
<option default value="0">-- Select One --</option>
<option value="1">Hot</option>
<option value="2">Cold</option>
</select>
<div class="hot">
This is hot!
</div>
<div class="cold">
This is cold!
</div>
</div>
CSS
.hot,
.cold {
display: none;
}
.display {
display:block;
}
jQuery
$('.type').change(function(){
var select_val = $(this).val();
var wrap = $(this).parent();
if(select_val == 1){
$('.hot', wrap).addClass('display');
$('.cold', wrap).removeClass('display');
}else if(select_val == 2 ){
$('.cold', wrap).addClass('display');
$('.hot', wrap).removeClass('display');
}
});
and Working Demo
Upvotes: 0
Reputation: 537
You want to get the parent of the select control that is changing, and then find the div with the matching class that will be show, something like this:
$('select').on('change', function() {
var selectedTxt = $(this).find(':selected').text().toLowerCase();
$(this).parent('.wrap').find('div').css('display','none')
$(this).parent('.wrap').find('div.'+selectedTxt ).css('display','block');
});
Upvotes: 1