Reputation: 2577
I have a select option that, when selected, is supposed to show the appropriate sections. By default everything is set to display:none
.
In this instance, if June is selected, then I want it to show all divs that have the class of june
.
$('#list').change(function() {
if ($(this).val() == "june") {
$('.june').css('display', 'block')
}
});
The code works as it should. However, I would like to write this more efficiently because I plan on adding additional months. To that end, how would I go about doing something along the lines of this:
$('#list').change(function() {
if ($(this).val() == {
thischosenmonth
}) {
$('.{thischosenmonth}').css('display', 'block')
}
});
where thischosenmonth
coincides with the month chosen by the user?
Upvotes: 0
Views: 33
Reputation:
You can set all months to display:none;
first (I will use hide()
for that), then use the value of the dropdown to set display:block;
for the corresponding month selection (I will use show()
for that). So if the HTML looked something like this (with more months obviously):
<select id='sel-month'>
<option disabled selected>Choose a Month</option>
<option value='january'>January</option>
<option value='february'>February</option>
<option value='march'>March</option>
</select>
<div class='month january'>This is the January box.</div>
<div class='month february'>This is the February box.</div>
<div class='month march'>This is the March box.</div>
You could use a script like this to show the corresponding month's information when the dropdown is changed:
$('#sel-month').change(function(){
$('.month').hide();
$('.' + $(this).val()).show();
});
Here's a fiddle: https://jsfiddle.net/1yk44zbq/
Upvotes: 2