0

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?

2
  • 1
    You can use variables inside of the jQuery selectors! $('.'+userInput).css('display', 'block') How are you retrieving the user input? Commented Jul 25, 2016 at 22:40
  • 2
    How about $('.' + $(this).val()).show(); inside your change event? Instead of using the IF for each one? If they all had the same class too, like class='june month', then you could call $('.month').hide() first to hide all other months that don't apply. Commented Jul 25, 2016 at 22:42

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.